关于vue组件中使用防抖/节流函数

概念

函数防抖(debounce):
在事件被触发n秒后再执行回调函数。若在这n秒内又被触发,则重新计时。典型的案例:【输入搜索】:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时。

应用场景:

  • search搜索联想,用户在不断输入值时,用防抖来节约请求资源。
  • window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次。

函数节流(throttle):
规定在一个单位时间内,只能触发一次函数。若这个单位时间内触发多次函数,只有一次生效。 典型的案例:鼠标不断点击触发,规定在n秒内多次点击只有一次生效。

应用场景:

  • 鼠标不断点击触发,mousedown(单位时间内只触发一次)。
  • 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断。

使用

在utils文件夹中新建utils.js,在需要使用到防抖/节流函数时引用。

/**
 * @description: 防抖函数
 * @param {type}:callback 回调函数
 * @param {type}:wait 节流时间(默认1000ms)
 * @return: 函数
 */
export function debounce(callback, wait = 1000) {
     
	var timeId = null;
	// 闭包的应用
	return function () {
     
		var self = this;
		var args = arguments;
		// 清除可能存在的timeId
		if (timeId !== null) {
     
			clearTimeout(timeId);
 		}
		timeId = setTimeout(() => {
     
			// TODO: 必须使用apply或者call,将回调函数的this指向Vue
			callback.apply(self, args);
 		}, wait)
	}
}

/**
 * @description: 节流函数
 * @param {type}:callback 回调函数
 * @param {type}:wait 节流时间(默认1000ms)
 * @return: callback 函数
 */
export function throttle (callback, wait = 1000) {
     
  var timeId = null
  var startTime = new Date()
  return function () {
     
    var self = this
    var args = arguments
    if (timeId !== null) {
     
      clearTimeout(timeId)
    }
    var currentTime = new Date()
    // 当前的时间差
    var spaceTime = currentTime - startTime
    if (spaceTime >= wait) {
     
      // TODO:调用apply或者call将this指向Vue
      callback.apply(self, args)
      // 执行完之后需要重置开始的时间
      startTime = new Date()
    } else {
     
      timeId = setTimeout(() => {
     
        // TODO:调用apply或者call将this指向Vue
        callback.apply(self, args)
      }, wait)
    }
  }
}

在vue组件中使用。

// 步骤1:在vue组件中引用(这里只演示throttle函数)
import {
      throttle } from '@/utils/utils.js';
<template>
	<button @click="btn" />
</template>

// 步骤2:在methods中使用
<script>
export default {
     
	methods: {
     
		/* TODO:这里需要注意两点:
		1、防抖/节流函数作为触发事件对象的value(值),而不是在触发事件的函数体内执行;
		2、若你想使用this关键字访问到Vue实例,
			那么-->防抖/节流回调函数必须使用function关键字声明,
			不能使用箭头函数(因为箭头函数的this是由创建函数的上下文决定的),
			若使用箭头函数this是undefined。
		*/
		btn: throttle(function () {
     
			console.log('节流');
			console.log('Vue实例', this);
			// ...doSomething
		}, 500)
		
		// 防抖同理使用
	}
};
</script>

结语:

希望该文章给对于在vue中使用防抖/节流函数的小伙伴有帮助!若有不足之处,欢迎留言交流,谢谢!

你可能感兴趣的:(vue,vue,javascript)