Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用防抖 #27

Open
YBFACC opened this issue Jul 13, 2020 · 0 comments
Open

使用防抖 #27

YBFACC opened this issue Jul 13, 2020 · 0 comments
Labels

Comments

@YBFACC
Copy link
Owner

YBFACC commented Jul 13, 2020

使用防抖

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

方式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官方文档

@YBFACC YBFACC added the Vue label Jul 13, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant