vue中使用閉包(防抖和節(jié)流)失效問題
1. 出現(xiàn)問題
防抖/節(jié)流使用無效,(例如防抖,按鈕點擊多次依舊執(zhí)行多次)
----> 查看是閉包無效,定義的局部變量依舊為初值
----> 沒有相應(yīng)清除定時器
? <el-button @click="btn1">按 鈕1</el-button> ? <el-button @click="debounce(btn2)">按 鈕2</el-button> </template> <script setup lang="ts"> // 以下方法調(diào)用不生效 const btn1 = () => { ? debounce(() => { ? ? console.log('點擊了') ? }, 1000)() } const btn2 = () => { ? console.log('點擊了'); } </script>
2. 問題原因
直接調(diào)用了防抖函數(shù)
原因:這個和vue的事件綁定原理有關(guān)。如果直接在函數(shù)體內(nèi)部使用的話,結(jié)果就是,一個匿名的立即執(zhí)行函數(shù)來進行執(zhí)行。由于每次觸發(fā)點擊事件都會返回一個新的匿名函數(shù), 就會生成一個新的函數(shù)執(zhí)行期上下文(稱之為執(zhí)行棧),所以就會防抖/節(jié)流就會失效
3. 解決辦法
<template> ? <el-button @click="btn">按 鈕1</el-button> </template> <script setup lang="ts"> const btn = debounce(function() { ? console.log('點擊了'); },500) </script>
4. 防抖節(jié)流函數(shù)
type DebouncedFn<T extends (...args: any[]) => any> = (this: ThisParameterType<T>, ...args: Parameters<T>) => void; type ThrottledFn<T extends (...args: any[]) => any> = (this: ThisParameterType<T>, ...args: Parameters<T>) => void; function debounce<T extends (...args: any[]) => any>(fn: T, delay: number, immediate = false): DebouncedFn<T> { ? let timer: number | null = null; ? return function(this: ThisParameterType<T>, ...args: Parameters<T>) { ? ? // if (timer !== null) clearTimeout(timer); ? ? timer && clearTimeout(timer) ? ? if (immediate) { ? ? ? const callNow = !timer; ? ? ? timer = setTimeout(() => { ? ? ? ? timer = null; ? ? ? }, delay); ? ? ? callNow && fn.apply(this, args); ? ? } else { ? ? ? timer = setTimeout(() => { ? ? ? ? fn.apply(this, args); ? ? ? }, delay); ? ? } ? }; } function throttle<T extends (...args: any[]) => any>(fn: T, delay: number, immediate = false): ThrottledFn<T> { ? let lastCall = 0; ? return function(this: ThisParameterType<T>, ...args: Parameters<T>) { ? ? const now = new Date().getTime(); ? ? // immediate 不為 true 時, 不立即執(zhí)行 ? ? lastCall === 0 && !immediate && (lastCall = now) ? ? const diff = now - lastCall; ? ? if (diff >= delay) { ? ? ? lastCall = now; ? ? ? fn.apply(this, args); ? ? } ? }; } export { ? debounce, ? throttle }
到此這篇關(guān)于vue中使用閉包(防抖和節(jié)流)失效問題的文章就介紹到這了,更多相關(guān)vue 閉包失效內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3利用組合式函數(shù)和Shared Worker實現(xiàn)后臺分片上傳
這篇文章主要為大家詳細介紹了Vue3如何利用組合式函數(shù)和Shared Worker實現(xiàn)后臺分片上傳(帶哈希計算),感興趣的小伙伴可以跟隨小編一起學習一下2023-10-10利用vuex-persistedstate將vuex本地存儲實現(xiàn)
這篇文章主要介紹了利用vuex-persistedstate將vuex本地存儲的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04