vue在watch中使用防抖

debouce.js

这里需要用call、apply来改变fn的this指向,不然fn的this指向是不明确的。如果这里没有改变fn的指向,那么在vue实例中的函数内部,获取到的this就是undefined。

// 第一种:
export const debounce = function (fn, delay) {
  let timer = null
  return function (value) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.call(this, value)
    }, delay)
  }
}

// 第二种:
export function debounce (fn, delay) {
  let timer = null
  return function () {
    clearTimeout(timer)
    const args = arguments
    const that = this
    timer = setTimeout(function () {
      fn.apply(that, args) // 这里的that是上一层函数的this
    }, delay)
  }
}

search.vue

  watch: {
    // searchText是输入框的值
    searchText: {
      handler: debounce(function (value) {
        this.getSearchSuggesion(value) // 这个是请求后台数据的函数。
      }, 500),
      immediate: true
    }
  },

猜你喜欢

转载自blog.csdn.net/autumnmn/article/details/125904743