Vue2.x-使用防抖以及节流的示例
导读:收集整理的这篇文章主要介绍了Vue2.x-使用防抖以及节流的示例,觉得挺不错的,现在分享给大家,也给大家做个参考。 目录utils:vue中使用:解释: 防抖: 节流:utils:/...
收集整理的这篇文章主要介绍了Vue2.x-使用防抖以及节流的示例,觉得挺不错的,现在分享给大家,也给大家做个参考。 目录
- utils:
- vue中使用:
- 解释:
- 防抖:
- 节流:
utils:
// 防抖export const debounce = (func, wait = 3000, immediate = true) =>
{
let timeout = null;
return function() {
let context = this;
let args = @R_406_643@s;
if (timeout) clearTimeout(timeout);
if (immediate) {
VAR callNow = !timeout;
//点击第一次为true 时间内点击第二次为false 时间结束则重复第一次 timeout = setTimeout(() =>
{
timeout = null;
}
, waIT);
//定时器ID if (callNow) func.apply(context, args);
}
else {
timeout = setTimeout(function() {
func.apply(context, args);
}
, wait);
}
}
;
}
;
// 时间戳方案export const throTTLeTime = (fn, wait = 2000) =>
{
var PRe = Date.now();
return function() {
var context = this;
var args = arguments;
var now = Date.now();
if (now - pre >
= wait) {
fn.apply(context, args);
pre = Date.now();
}
}
;
}
;
// 定时器方案export const throttleSetTimeout = (fn, wait = 3000) =>
{
var timer = null;
return function() {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
fn.apply(context, args);
timer = null;
}
, wait);
}
}
;
}
;
vue中使用:
template>
div class="main">
p>
防抖立即执行/p>
button @click="click1">
点击/button>
br />
p>
防抖不立即执行/p>
button @click="click2">
点击/button>
br />
p>
节流时间戳方案/p>
button @click="click3">
点击/button>
br />
p>
节流定时器方案/p>
button @click="click4">
点击/button>
/div>
/template>
script>
import {
debounce, throttleTime, throttleSetTimeout }
From './utils';
export default {
methods: {
click1: debounce( function() {
console.LOG('防抖立即执行');
}
, 2000, true ), click2: debounce( function() {
console.log('防抖不立即执行');
}
, 2000, false ), click3: throttleTime(function() {
console.log('节流时间戳方案');
}
), click4: throttleSetTimeout(function() {
console.log('节流定时器方案');
}
) }
,}
;
/script>
style scoPEd lang="scss">
* {
margin: 0;
font-Size: 20px;
user-select: none;
}
.main {
position: absolute;
left: 50%;
transform: translatex(-50%);
width: 500px;
}
button {
margin-bottom: 100px;
}
/style>
解释:
防抖:
立即执行版本:immediate为true,则点击第一次就执行,再继续点击则不执行,当wait时间结束后,再点击则生效,也就是只执行第一次。
原理:
点击第一次不存在timeoutID,并且callNow为true,则立即执行目标代码,点击第二次时存在了timeoutID,并且callNow为false,所以不执行目标代码,当wait时间结束后,把timeoutID设为null,则开始重复立即执行逻辑。
不立即执行版:immediate为false,则点击第一次不执行,当wait时间结束后,才生效,也就是无论点击多少次,只执行最后一次点击事件
原理:
使用setTimeout延迟执行事件,如果多次触发,则clearTimeout上次执行的代码,重新开始计时,在计时期间没有触发事件,则执行目标代码。
节流:
连续触发事件时以wait频率执行目标代码。
效果:
以上就是Vue2.x-使用防抖以及节流的示例的详细内容,更多关于vue 防抖及节流的资料请关注其它相关文章!
您可能感兴趣的文章:- Vue组件中使用防抖和节流实例分析
- vue中防抖和节流的使用方法
- vue函数防抖与节流的正确使用方法
- 浅析VUE防抖与节流
- Vue 中使用lodash对事件进行防抖和节流操作
- Vue中使用防抖与节流的方法
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Vue2.x-使用防抖以及节流的示例
本文地址: https://pptw.com/jishu/594674.html
