手把手教你在vue中使用自定义指令全局封装防抖节流函数

第一步在src下创建utils文件夹并创建common.js文件

//'@/utils/common.js' 文件
 
 
function throttle(bindObj, fn, delay) {
    
    
	bindObj.$$prevTime = Date.now()
	return function(...args) {
    
    
		const nowTime = Date.now()
		if(nowTime - bindObj.$$prevTime > delay) {
    
    
			fn.apply(this, args)
			bindObj.$$prevTime = nowTime
		}
	}
}
 
function debounce(bindObj, fn, delay) {
    
    
	return function(...args) {
    
    
		bindObj.$$timer && clearTimeout(bindObj.$$timer)
		bindObj.$$timer = setTimeout(() => {
    
    
			fn.apply(this, args)
		}, delay)
	}
}
 
export {
    
    
	debounce,
	throttle
}

第二步在src下创建plugin文件夹并创建index.js文件

// '@/plugin/index.js'文件
 
import Vue from 'vue'
import {
    
     debounce, throttle } from '../units/common'
 
Vue.directive('debounce', {
    
    
	bind(el, binding, vnode) {
    
    
		const [emit, fn, delay=1000] = binding.value
		el.addEventListener(emit, debounce(vnode, fn, delay))
	}
})
 
Vue.directive('throttle', {
    
    
	bind(el, binding, vnode) {
    
    
		const [emit, fn, delay=1000] = binding.value
		el.addEventListener(emit, throttle(vnode, fn, delay))
	}
})

第三步在全局main.js中进行引入

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import  "./plugin/index"
Vue.config.productionTip = false;
new Vue({
    
    
  router,
  render: (h) => h(App),
}).$mount("#app");

最后就可以在想要使用的组件内进行使用了

传参是一个数组,参数分别是事件类型,事件执行函数以及时间(默认为1秒,也可以不传)

///防抖   (只执行最后一次)
<template>
  <div>
    <input type="button" v-debounce="['click', jiantin]" value="点击" />
    <h1>{
    
    {
    
     num }}</h1>
  </div>
</template>
 
<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      num: 0,
    };
  },
  methods: {
    
    
    jiantin() {
    
    
      this.num++;
    },
  },
};
</script>
 
<style>
</style>
//节流  (在一段时间内只执行一次)
<template>
  <div>
    <input type="button" v-throttle="['click', jiantin, 3000]" value="点击" />
    <h1>{
    
    {
    
     num }}</h1>
  </div>
</template>
 
<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      num: 0,
    };
  },
  methods: {
    
    
    jiantin() {
    
    
      this.num++;
    },
  },
};
</script>
 
<style>
</style>

猜你喜欢

转载自blog.csdn.net/qq_47272950/article/details/124471002