"节流"是一种控制事件触发频率的技术。当某个事件被触发时,节流能够确保事件处理函数不会立即执行,而是在一定的时间间隔之后执行。这有助于减少事件处理函数的执行次数,特别是在处理频繁触发的事件(比如滚动、调整窗口大小、输入框输入等)时,以提高性能和减轻不必要的计算负担。
#创建throttle.js
const throttle = (fn, delay) => {
let last = 0
return function () {
const now = Date.now()
if (now - last >= delay) {
fn.apply(this, arguments)
last = now
}
}
}
export default {
mounted(el, binding) {
const { value, arg } = binding
const delay = arg ? parseInt(arg, 10) : 1000
const throttledClick = throttle(value, delay)
el.__throttledClick__ = throttledClick
el.addEventListener('click', throttledClick)
},
beforeUnmount(el) {
console.log('Before unmount')
if (el) {
console.log(el)
console.log(el.__throttledClick__)
el.removeEventListener('click', el.__throttledClick__)
delete el.__throttledClick__
}
}
}
import throttleDirective from '@/utils/throttle' // 注册全局指令
app.directive('throttle', throttleDirective)
//这里面默认1000 可自定义时间
<el-button type="primary" v-throttle="opneDialog"> 添加机构 </el-button>
<el-button type="primary" v-throttle:3000="opneDialog"> 添加机构 </el-button>
!!!注意事项
// 这种写法 需要把单独写为方法 才可以正常使用
<el-button @click="formVisible = true"> 添加机构 </el-button>