如何优雅的在vue中使用防抖和节流
时间: 2023-07-15 12:15:14 浏览: 86
在 Vue 中使用防抖和节流可以通过自定义指令或者混入 (mixin) 的方式实现。下面是一个使用混入的示例代码:
```
// debounce.js
import _ from 'lodash'
export default {
data () {
return {
debounceTimer: null
}
},
methods: {
// 防抖函数
debounce (func, wait = 500) {
if (this.debounceTimer) {
clearTimeout(this.debounceTimer)
}
this.debounceTimer = setTimeout(() => {
func()
}, wait)
}
}
}
// throttle.js
import _ from 'lodash'
export default {
data () {
return {
throttleTimer: null
}
},
methods: {
// 节流函数
throttle (func, wait = 500) {
if (!this.throttleTimer) {
this.throttleTimer = setTimeout(() => {
func()
this.throttleTimer = null
}, wait)
}
}
}
}
```
然后在需要使用防抖或节流的组件中混入即可:
```
import debounce from '@/mixins/debounce'
import throttle from '@/mixins/throttle'
export default {
mixins: [debounce, throttle],
methods: {
handleClick () {
// 使用防抖
this.debounce(() => {
console.log('click')
})
// 使用节流
this.throttle(() => {
console.log('scroll')
})
}
}
}
```
当然,这里使用的是 lodash 库提供的防抖和节流函数,如果你不想使用第三方库,也可以自己实现防抖和节流函数。