Vue2之防抖_debounce封装函数&v-debounce自定义指令(传参/不传)

目录

1、防抖

2、debounce - 封装函数

3、v-debounce 全局自定义指令


1、防抖

推荐文章 :

https://blog.csdn.net/weixin_58099903/article/details/119902796


2、debounce - 封装函数

utils / tools.js

/**
 * 函数防抖 是n秒后延迟执行,多用于页面scroll滚动,窗口resize,防止按钮重复点击
 * @param {Function} fn 是我们需要包装的事件回调
 * @param {Number} delay 是每次推迟执行的等待时间
 * @returns
 */
export default function (fn, delay) {
	// 记录上一次触发的时间
	var timer = null;
	return function () {
		// 保留调用时的this上下文
		var context = this;
		// 保留调用时传入的参数
		var args = arguments;
		// 每次事件被触发时,都去清除上一次延时器
		if (timer) clearTimeout(timer);
		// 设立新的定时器
		timer = setTimeout(function () {
			fn.apply(context, args);
		}, delay);
	};
};

使用 :

<template>
  <div>
    <!-- debounce封装函数用法 -->
    <el-button @click="submitForm(item.id)">防抖</el-button>
  </div>
</template>

<script>
import { debounce } from '../utils/tools';

export default {
  methods: {
    submitForm: debounce(function (id) {
      console.log('防抖', id);
    }, 1000),
  },
};
</script>

3、v-debounce 全局自定义指令

utils / directives.js

/**
 * v-debounce 防抖指令 防止重复点击
 * @param {Function} fn 方法名【必传】
 * @param {*} params 函数参数
 * @param {String} event 触发方式click
 * @param {Number} delay 防抖时间1000
 */
const debounce = Vue.directive('debounce', {
	inserted: function (el, binding) {
		let timer; // 定时器
		const { fn, params, event, delay } = binding.value;
		el.addEventListener(event || 'click', () => {
			// 每次事件被触发时,都去清除之前旧的定时器
			if (timer) clearTimeout(timer);
			// 设立新的定时器
			if (binding.value.hasOwnProperty('params')) {
				// 传参用法:v-debounce="{ fn: 方法名, params: '传参', delay: 防抖时间 }"
				timer = setTimeout(() => {
					fn(params);
				}, delay || 1000);
			} else {
				// 不传参用法:v-debounce="方法名"
				timer = setTimeout(() => {
					binding.value();
				}, 1000);
			}
		});
	},
});

export { debounce };

使用 :

// main.js 中引用
import "./utils/directives";
<!-- 不传参用法 -->
<el-button v-debounce="submitForm">防抖</el-button>
<!-- 传参用法 -->
<el-button
  v-debounce="{
    fn: submitForm,
    params: item.id,
    event: 'click',
    delay: 1000,
  }"
  >防抖</el-button
>

  methods: {
    submitForm (id) {
      console.log('防抖', id);
    },
  },

猜你喜欢

转载自blog.csdn.net/weixin_58099903/article/details/133928603