个人在vue中使用防抖中一般会绑定vm实例做定时器的绑定对象,大家也可以根据自己的实际需求修改防抖节流的函数
//'@/utils/debounce.js' 文件
function throttle(bindObj, fn, delay) {
bindObj.$$prevTime = Date.now()
return function(...args) {
const nowTime = Date.now()
if(nowTime - bindObj.$$prevTime > delay) {
fn.apply(this, args)
bindObj.$$prevTime = nowTime
}
}
}
function debounce(bindObj, fn, delay) {
return function(...args) {
bindObj.$$timer && clearTimeout(bindObj.$$timer)
bindObj.$$timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
export {
debounce,
throttle
}
// '@/plugin/index.js'文件
import Vue from 'vue'
import { debounce, throttle } from '@/utils/debounce'
Vue.directive('debounce', {
bind(el, binding, vnode) {
const [emit, fn, delay=1000] = binding.value
el.addEventListener(emit, debounce(vnode, fn, delay))
}
})
Vue.directive('throttle', {
bind(el, binding, vnode) {
const [emit, fn, delay=1000] = binding.value
el.addEventListener(emit, throttle(vnode, fn, delay))
}
})
最后在main.js引入plugin
// main.js文件
....
import './plugin/index.js'
....
然后在我们需要使用防抖节流的地方用v-debounce 或者v-throttle
传参为一个数组 第一项是 事件类型(click/mousemove...) 第二项是事件函数 第三项是防抖节流的时间 可以不传 默认为1000ms
<template>
<div class="about">
<div class="box" v-debounce="['mousemove', addNum]">
<h1>{{num}}</h1>
</div>
</div>
</template>
<script>
export default {
data: () => ({
num: 0
}),
methods: {
addNum() {
this.num++
}
}
}
</script>
<style scoped="scoped">
.box {
width: 100px;
height: 100px;
background: skyblue;
}
</style>
?
?
|