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

Posted 老张在线敲代码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手把手教你在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>

以上是关于手把手教你在vue中使用自定义指令全局封装防抖节流函数的主要内容,如果未能解决你的问题,请参考以下文章

手把手教你在 Vue3 中自定义指令

手把手教你在 Vue3 中自定义指令

vue节流全局指令超级简单

vue中自定义指令组件化生命周期节流和防抖获取DOMmint-ui简介过渡和动画

松哥手把手教你在 Vue3 中自定义插件

松哥手把手教你在 Vue3 中自定义插件