我对输入框的input事件进行了监听:
<el-input v-model="amount" @input="isValid"></el-input>
当用户输入非有效数字时,我将会弹框提示非法输入:
if (isNaN(this.amount)) this.$message({message: 'invalid input'});
为了防止监听函数频繁触发,我给该函数做了防抖:
let debounce = (fn , wait = 500) => {
let timer = null;
return function () {
let context = this;
let args = arguments;
if(timer){
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
fn.apply(context,args);
},wait);
};
};
export default debounce;
于是,我就有了两种写法:
(1)写法一:
methods:{
isValid() {
let context = this;
this.$util.debounce(function () {
if (isNaN(context.new_bill.amount))
context.$message({message: 'invalid input'});
});
}
}
(2)写法二:
methods:{
isValid: util.debounce(function () {
if (isNaN(this.new_bill.amount))
this.$message({message: 'invalid input');
}),
}
结果是,只有写法二有效,写法一无效,请问这是为什么呢?写法一我思考了很久,感觉我已经认真处理好了this指向的问题,但是却依旧没有用。
从方法二可以推导出debounce可以返回一个函数,那么问题就来了,你方法一中生成了函数后,没有运行!!
另外,就算可以运行,方法一也是错的,因为每次debounce生成的函数都是新的,都会执行,不能达到防抖节流的目的。
这和this指向无关