函数被频繁调用时,会出现性能问题,此时就需要进行节流操作 节流操作主要是在一定的时间内同一事件无论触发多少次,对应的事件处理函数都只是每间隔规定事件执行一次

下面封装了节流函数

可以在utils文件夹下新建throttle.js

 // 节流函数
const throttle=(func, delay) => {
	// 缓存一个定时器
	let timer = null
	// 这里返回的函数是每次实际调用的节流函数 
	return function(...args) {
		if (!timer) { //判断timer是否有值,如果没有则说明定时器不存在即可继续执行
			timer = setTimeout(() => { //关
				func.apply(this, arguments)
				timer = null; //开
			}, delay)
		}
	}
}
export default throttle

使用格式如下

<template>
<button @click="onTapItems(item,index)"></button>
<template>

<script>
import throttle from "/utils/throttle"
onTapItems: throttle(function(item,index){
				console.log(item,index);
			},500)
<script>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐