我正在尝试运行在Vue.js中调用query()
的组件属性q
被修改时调用的方法。
失败是因为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();
},
},
Run Code Online (Sandbox Code Playgroud)
错误:
TypeError:_this2.query不是函数
如果我debounce()
按以下方式编写呼叫TypeError: expected a function
,则页面加载时错误会更早出现。
debouncedQuery: _.debounce(this.query, 300),
Run Code Online (Sandbox Code Playgroud)
Pad*_*rom 13
问题来自您在中定义的箭头功能的词法范围_.debounce
。this
绑定到您要在其中定义的对象,而不是实例化的Vue实例。
如果将箭头功能切换为常规功能,则范围将正确绑定:
methods: {
// ...
debouncedQuery: _.debounce(function () { this.query(); }, 300)
}
Run Code Online (Sandbox Code Playgroud)
我们可以通过简单的 JS (ES6) 用几行代码来完成:
function update() {
if(typeof window.LIT !== 'undefined') {
clearTimeout(window.LIT);
}
window.LIT = setTimeout(() => {
// do something...
}, 1000);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2743 次 |
最近记录: |