Vue中对防抖和节流的封装可以通过自定义指令或者混入Mixin进行实现。
防抖指令的封装:
export default {
inserted(el, binding) {
let timer;
el.addEventListener('input', () => {
if(timer) clearTimeout(timer);
timer = setTimeout(() => {
binding.value();
}, binding.arg || 1000);
})
}
}
import Vue from 'vue'
import debounce from './debounce.js'
Vue.directive('debounce', debounce)
<template>
<input v-debounce="handleInput" :placeholder="提示内容">
</template>
<script>
export default {
methods: {
handleInput() {
}
}
}
</script>
节流Mixin的封装:
export default {
data() {
return {
throttleTimer: null,
canRun: true
}
},
methods: {
throttle(fn, delay=500) {
if(!this.canRun) return;
this.canRun = false;
fn();
this.throttleTimer = setTimeout(() => {
clearTimeout(this.throttleTimer);
this.canRun = true;
}, delay)
}
},
beforeDestroy() {
if(this.throttleTimer) {
clearTimeout(this.throttleTimer);
this.throttleTimer = null
}
}
}
import throttle from './throttle.js'
export default {
mixins: [throttle],
methods: {
handleScroll() {
this.throttle(() => {
})
}
}
}