Vue2.x-使用防抖以及節(jié)流的示例
utils:
// 防抖
export const debounce = (func, wait = 3000, immediate = true) => {
let timeout = null;
return function() {
let context = this;
let args = arguments;
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>防抖立即執(zhí)行</p>
<button @click="click1">點擊</button>
<br />
<p>防抖不立即執(zhí)行</p>
<button @click="click2">點擊</button>
<br />
<p>節(jié)流時間戳方案</p>
<button @click="click3">點擊</button>
<br />
<p>節(jié)流定時器方案</p>
<button @click="click4">點擊</button>
</div>
</template>
<script>
import { debounce, throttleTime, throttleSetTimeout } from './utils';
export default {
methods: {
click1: debounce(
function() {
console.log('防抖立即執(zhí)行');
},
2000,
true
),
click2: debounce(
function() {
console.log('防抖不立即執(zhí)行');
},
2000,
false
),
click3: throttleTime(function() {
console.log('節(jié)流時間戳方案');
}),
click4: throttleSetTimeout(function() {
console.log('節(jié)流定時器方案');
})
},
};
</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>
解釋:
防抖:
立即執(zhí)行版本:immediate為true,則點擊第一次就執(zhí)行,再繼續(xù)點擊則不執(zhí)行,當wait時間結束后,再點擊則生效,也就是只執(zhí)行第一次。
原理:
點擊第一次不存在timeoutID,并且callNow為true,則立即執(zhí)行目標代碼,點擊第二次時存在了timeoutID,并且callNow為false,所以不執(zhí)行目標代碼,當wait時間結束后,把timeoutID設為null,則開始重復立即執(zhí)行邏輯。
不立即執(zhí)行版:immediate為false,則點擊第一次不執(zhí)行,當wait時間結束后,才生效,也就是無論點擊多少次,只執(zhí)行最后一次點擊事件
原理:
使用setTimeout延遲執(zhí)行事件,如果多次觸發(fā),則clearTimeout上次執(zhí)行的代碼,重新開始計時,在計時期間沒有觸發(fā)事件,則執(zhí)行目標代碼。
節(jié)流:
連續(xù)觸發(fā)事件時以wait頻率執(zhí)行目標代碼。
效果:

以上就是Vue2.x-使用防抖以及節(jié)流的示例的詳細內容,更多關于vue 防抖及節(jié)流的資料請關注腳本之家其它相關文章!
相關文章
vue-element-admin按鈕級權限管控的實現(xiàn)
開發(fā)離不開權限,不同的用戶登錄,根據(jù)不同的權限,可以訪問不同的管理目錄,本文主要介紹了vue-element-admin按鈕級權限管控的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2022-04-04
vue3.0報錯Cannot?find?module‘worker_threads‘的解決辦法
這篇文章介紹了vue3.0報錯Cannot?find?module‘worker_threads‘的解決辦法。對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-11-11

