在vue项目中使用封装好的防抖函数时拿不到vue实例的this,怎样才能拿到this?

新手上路,请多包涵

// 防抖函数

    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)
}
阅读 2.4k
1 个回答

我是可以获取到的,你看看你这个的 debounce 那里写的不对了?对照一下 lodash.debounce 看看?

看起来像是因为回调函数调用时没有改变 this 指向导致的。

其实也不用自己写,直接 npm i lodash.debounce 然后按需引入就好了。


哦,你这一说我发现问题了,不需要用箭头函数,直接用普通的匿名函数就行了。

handleSearch: debounce(
  function(value = '') {
    const params = {
      keywords: value,
      pageSize: 20,
      pageNum: 1
    }
    remoteSearchAPI(params).then((res) => {
      this.options = res.rows
    })
  },
  350,
  { maxWait: 1000 }
)
推荐问题