YBFACC / blog

仅记录个人学习使用
3 stars 0 forks source link

使用防抖 #27

Open YBFACC opened 3 years ago

YBFACC commented 3 years ago

使用防抖

对一个频繁触发的请求使用防抖。

方式1:

<script>
import debounce from '@/utils/debounce.js'
export default {
  data() {
    return {
      query: ''
    }
  },
  created() {
    this.$watch(
      'query',
      debounce(newQuery => {
        this.$emit('query', newQuery)
      }, 400)
    )
  }
}
</script>

方式2:

<script>
import debounce from '@/utils/debounce.js'
export default {
  data() {
    return {
      query: ''
    }
  },
  methods: {
    _debounce_: debounce(function(newQuery) {
      this.$emit('query', newQuery)
    }, 500),
  },
  watch: {
    query(newQuery) {
      this._debounce(newQuery)
    }
  },
}
</script>

debounce函数中不要使用箭头函数,因为箭头函数不能使用call。

注意,不应该使用箭头函数来定义 method 函数 (例如 plus: () => this.a++)。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.a 将是 undefined。

debounce文件:

export default function debounce(fun, delay) {
  let timer
  return function(...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fun.apply(this, args)
    }, delay)
  }
}

两种方式都是使用闭包保存定时器,来实现防抖的目的。

参考

代码参考

Vue官方文档