我正在尝试运行一个名为 query()
的方法当组件属性调用 q
在 Vue.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();
},
},
错误:
TypeError: _this2.query is not a function
如果我写
debounce()
如下调用,TypeError: expected a function
错误出现的时间更早,在页面加载时。debouncedQuery: _.debounce(this.query, 300),
最佳答案
问题来自您在 _.debounce
中定义的箭头函数的词法范围。 . this
绑定(bind)到您在其中定义它的对象,而不是实例化的 Vue 实例。
如果您将箭头功能切换为常规功能,则范围已正确绑定(bind):
methods: {
// ...
debouncedQuery: _.debounce(function () { this.query(); }, 300)
}
关于javascript - Lodash 的 _.debounce() 在 Vue.js 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53041171/