Vue-cli 3.x 自定义指令
本文例子是自定义指令实现防抖和节流,其它指令实现类似
1.vue-cli中新建指令集文件夹
在src目录下创建directives文件夹,并在directives中创建index.js文件,结构如图:
2.写入指令
在新建的index.js文件中写入指令并抛出
//自定义指令集
export default (app) => {
/***
* 防抖 单位时间只触发最后一次
* @param {?Number|300} time - 间隔时间
* @param {Function} fn - 执行事件
* @param {?String|"click"} event - 事件类型 例:"click"
* @param {Array} binding.value - [fn,event,time]
* @date 2020-1-29
* @author aChuan
* 例:<el-button v-debounce="[reset,`click`,300]">刷新</el-button>
* 也可简写成:<el-button v-debounce="[reset]">刷新</el-button>
*/
app.directive('debounce', (el, binding) => {
let [fn, event = "click", time = 300] = binding.value
let timer
el.addEventListener(event, () => {
timer && clearTimeout(timer)
timer = setTimeout(() => fn(), time)
})
})
/***
* 节流 每单位时间可触发一次
* 第一次瞬间触发,最后一次不管是否达到间隔时间依然触发
* 【考虑到input的change事件】
* @param {?Number|300} time - 间隔时间
* @param {Function} fn - 执行事件
* @param {?String|"click"} event - 事件类型 例:"click"
* @param {Array} binding.value - [fn,event,time]
* @date 2020-1-31
* @author aChuan
* 例:<el-button v-throttle="[reset,`click`,300]">刷新</el-button>
* 传递参数则:<el-button v-throttle="[()=>reset(param),`click`,300]">刷新</el-button>
*/
app.directive('throttle', (el, binding) => {
let [fn, event = "click", time = 300] = binding.value
let timer, timer_end;
el.addEventListener(event, () => {
if (timer) {
clearTimeout(timer_end);
return timer_end = setTimeout(() => fn(), time);
}
fn();
timer = setTimeout(() => timer = null, time)
})
})
}
3.main.js中引入
import { createApp } from 'vue'
import App from './App.vue'
import directives from "./directives/index.js"
const app = createApp(App)
//载入自定义指令
directives(app)
app.mount('#app')
4.组件中使用
<button v-debounce="[add,'click',500]">点击(防抖)</button>