vue节流功能,防止表单频繁重复提交,方法频繁重复调用等
1.安装依赖:
npm install lodash.throttle
2.入口文件main.js全局引入
import { throttle, debounce } from 'lodash';
// 将throttle挂载到Vue原型上
Vue.prototype.$throttle = throttle
Vue.prototype.$debounce = debounce
3.1在vue页面中使用(连续点击只执行第一次):
<div class="myCenter" id="article-like" @click="throttledLikeLabel">
<span style="cursor: pointer;" v-if="is_like===false">赞🤍</span>
<span style="color: red;cursor: pointer;" v-else>赞💖</span>
</div>
3.2:在生命周期钩子函数中调用:
//this.likeLabel()为原始函数
//this.throttledLikeLabel表示声明的节流函数
mounted() {
this.throttledLikeLabel = this.$throttle(this.likeLabel, 5000,
, {
leading: true, // 执行第一次点击
trailing: false // 不执行最后一次点击
});//5000表示每5秒最多执行一次
},
4.如果函数有参数,则写法案例如:
mounted() {
// 创建带参数的节流函数
this.throttledLikeLabel = this.$throttle((articleId, userId) => { this.likeLabel(articleId, userId) }, 5000, {
leading: true, // 执行第一次点击
trailing: false // 不执行最后一次点击
})
},
===========防抖函数,如果连续点击只需要执行最后一次===========
this.throttledLikeLabel = this.$debounce(this.likeLabel, 5000)

浙公网安备 33010602011771号