-
在utils/tool.js文件里定义节流函数
/** * 函数节流 * @param {Function} fn 执行函数 * @param {Number} delay 间隔时间 */ export function throttle(fn, delay) { let previous = 0 let _this = this return function (args) { const _args = args const now = Date.now() if (now - previous > delay) { fn.call(_this, _args) previous = now } } }
-
在directives/index.js文件里写自定义指令
import Vue from 'vue' import { throttle } from '@/utils/tool' /** * 节流指令 v-throttle */ Vue.directive('throttle', { bind(el, binding) { let execFunc if (binding.value instanceof Array) { const [func, time = 500] = binding.value execFunc = throttle(func, time) } else { execFunc = throttle(binding.value, 500) } el.addEventListener('click', execFunc) }, })
-
在main.js里全局引入
import '@/directives/index'
-
使用
<el-button type="primary" v-throttle.click.stop="addConfirm" :loading="btnLoading">确 定</el-button>
自定义指令:全局节流指令v-throttle
于 2022-04-15 10:47:07 首次发布