我试图运行一个名为query()的方法,但Vue中的组件属性名为q.js被修改了.

这失败了,因为this.query()是未定义的.This指的是我的组件的实例,但不知何故不包含这些方法.

下面是相关的代码部分,我试图查看组件属性q并运行query()函数:

methods: {
  async query() {
    const url = `https://example.com`;
    const results = await axios({
      url,
      method: 'GET',
    });
    this.results = results.items;
  },
  debouncedQuery: _.debounce(() => { this.query(); }, 300),
},
watch: {
  q() {
    this.debouncedQuery();
  },
},

错误:

Type错误: _this2.query is not a function

If I write the debounce() call as below, the Type错误: expected a function error appears even earlier, at the page load.

debouncedQuery: _.debounce(this.query, 300),

推荐答案

这个问题来自您在_.debounce中定义的箭头函数的词法范围.this绑定到要在其中定义它的对象,而不是实例化的Vue实例.

如果将箭头函数切换为常规函数,则范围将正确绑定:

methods: {
  // ...
  debouncedQuery: _.debounce(function () { this.query(); }, 300)
}

Vue.js相关问答推荐

元素不会对react 性props 的更改做出react

如何以惯用的方式触发 vue3 中同级组件的效果?

Vuetify右侧并排switch

如何在Vue3中使用vuechartjs 5.2从父组件更新图表

如何在 vue2.7 中删除 slot-scope

为什么我在 Vue npm run serve 的 localhost 中得到无法获取

如何使用 vue 或 javascript 向服务器发送密码?

指定一个 vue-cli vue.config.js 位置

Vue.js 中的 mount挂载是什么意思?

如何将Vue的主应用程序渲染到body元素?

Vue test-utils 如何测试 router.push()

使用 Blade/Mustache 模板混合 Laravel 和 Vue.Js

使用vue.js单击时如何获取按钮的值

Vuetify - 根据另一个 Select 选项过滤 Select 数据

如何使用 VueJS / Typescript 导入 JSON 文件?

如何通过 Axios 发送文件到 Laravel

使计算的 Vue 属性依赖于当前时间?

在 Vue.js 模板中调用函数

表格行上的 Vuejs 转换

Vue.js 无法读取 null 的属性 length长度