// 防抖函数
export function debounce (fn, delay) {
let timeout = null
return function () {
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(fn, delay)
}
}
// 使用时
methods:{
aaa: debounce(() => {
console.log(this)
// 在这里的this是不存在的,我应该怎么才能拿到这个this???
}, 500)
}
我是可以获取到的,你看看你这个的
debounce
那里写的不对了?对照一下 lodash.debounce 看看?看起来像是因为回调函数调用时没有改变
this
指向导致的。其实也不用自己写,直接
npm i lodash.debounce
然后按需引入就好了。哦,你这一说我发现问题了,不需要用箭头函数,直接用普通的匿名函数就行了。