我知道对方法使用箭头语法将导致“ this”不映射到Vue实例,但是在我的示例中,我使用lodash.debounce,据我所知,我没有使用这里的箭头语法?
返回无法读取未定义的属性'$ emit'
methods: {
onChange: debounce(function(el) {
this.$emit('change', el.target.value)
}, 1000)
}
我在编写不带箭头符号的防反跳功能时是否存在语法错误?
答案 0 :(得分:1)
您的代码应该可以正常工作。您可以提供其他上下文吗?
稍有改进:通常最好在每个实例上创建去抖动功能,而不是在该组件的所有实例之间共享一个功能。
methods: {
onChange(e) {
this.$emit('change', e.target.value)
}
},
created() {
this.onChange = _.debounce(this.onChange, 1000)
}
这是一个可行的示例:
new Vue({
el: '#app',
data: {
text: '',
},
created() {
this.onClick = _.debounce(this.onClick, 1000)
},
methods: {
onClick() {
// this is not undefined here
this.text += 'Debounced! ';
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="onClick">Click Me</button>
<p>{{ text }}</p>
</div>