当Vue.js中名为q
的组件属性被修改时,我尝试运行名为query()
的方法。
这会失败,因为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();
},
},
错误:
类型错误:_this2.query不是函数
如果我按照下面的方式编写debounce()
调用,TypeError: expected a function
错误甚至会出现得更早,在页面加载时。
debouncedQuery: _.debounce(this.query, 300),
3条答案
按热度按时间izj3ouym1#
问题来自于您在
_.debounce
中定义的arrow函数的词法范围。this
绑定到您在其中定义它的对象,而不是示例化的Vue示例。如果将arrow函数切换为常规函数,则作用域的绑定正确:
nbysray52#
我们可以通过简单的JS(ES6)实现,只需几行代码:
vmjh9lq93#
正如在另一篇文章中所回答的,这在Vue中是未定义的,使用去抖动方法添加去抖动IMO的最好方法是在方法中创建方法,例如:
但是,然后将其替换在您创建的块中,例如: