背景:在开发中,我们经常会在搜索框中使用防抖或节流进行优化,因此为了方便,今天我们自定义一个(v-throttle)指令。
自定义指令语法:可参考官方文档
1.在项目的utils
目录下定义util.js
模块(通常该模块放一些通用的工具方法):
export const throttle = (callback, delay) => {
let timer = null
return (e) => {
if (!timer) {
timer = setTimeout(() => {
callback(e)
timer = null
}, delay)
}
}
}
2.在项目的directive
目录下定义throttle.js
模块(定义指令):
import { throttle } from '@/utils/util'
export default {
install(Vue, options = {}) {
Vue.directive('throttle', {
bind(el, binding) {
let execFunc
// 当绑定的函数带有参数,则binding.value是一个数组
if (binding.value instanceof Array) {
const [func, time = 500] = binding.value
execFunc = throttle(func, time)
} else {
// 当仅仅绑定一个函数名,则binding.value就是一个函数名
execFunc = throttle(binding.value, 500)
}
el.addEventListener('click', execFunc)
},
})
},
}
3.在项目的main.js
中注册v-throttle
指令:
import Vue from 'vue'
import Throttle from '@/utils/util'
Throttle.install()
4.在组件中使用:
<template>
<div class="container">
<input type="text"
v-model="queryString"
v-throttle="searchContent">
</div>
</template>
<script>
import { remoteSearch } from '@/api/xxxx'
export default {
name: 'test',
data () {
return {
queryString: ''
}
},
methods: {
async searchContent () {
var data = {
keyword: this.queryString
}
var res = await remoteSearch(data)
if (res.code === 0) {
//...
}
}
}
}
</script>
<style>
</style>
5.最后:实现一个自定义的指令并不难,根据场景选择合适的钩子函数进行相应的逻辑实现即可。