vue3 自定義指令(簡易版防抖、節流)



/*
 * @Descripttion: 自定義指令
 * @version:
 */
export const direcitiveFUc = (app: any) => {
    /*
    * @Descripttion: 防抖,單位時間內觸發最后一次
    * @param [function] func --執行事件
    * @param [?number|300] wait = 300 -- 時間間隔
    * @param [?string|"click"] event -- 事件類型
    * @param [?boolean|true] boolean -- 事件冒泡-false , 事件捕獲--true
    * @param [Array] binding.value - [func,type,wait,true]  
    * <a-button v-debounce="[test,'click',1000,true]">防抖測試</a-button>
    */
    app.directive('debounce', {
        beforeMount(el: any, binding: any) {
            let [
                func,
                type = 'click',
                wait = 300,
                immediate = true
            ] = binding.value;
            let timer: any
            el.$type = type;
            el.$handle = () => {
                timer && clearTimeout(timer)
                timer = setTimeout(() => func(), wait)
            }
            el.addEventListener(el.$type, el.$handle, immediate);
        },
        unmounted(el: any) {
            el.removeEventListener(el.$type, el.$handle);
        }
    })

    /*
    * @Descripttion: 節流,單位時間內可觸發一次
    * @param [function] func --執行事件
    * @param [?number|300] wait = 300 -- 時間間隔
    * @param [?string|"click"] event -- 事件類型
    * @param [?boolean|true] boolean -- 事件冒泡-false , 事件捕獲--true
    * @param [Array] binding.value - [func,type,wait,true]  
    * <a-button v-debounce="[throttle,'click',1000,true]">防抖測試</a-button>
    */
    app.directive('throttle', {
        beforeMount(el: any, binding: any) {
            let [
                func,
                type = 'click',
                wait = 300,
                immediate = true
            ] = binding.value;
            let timer: any, timer_end: any
            el.$type = type;
            el.$handle = () => {
                if (timer) {
                    clearTimeout(timer_end)
                    return timer_end = setTimeout(() => func, wait)
                }
                func()
                timer = setTimeout(() => null, wait);
            }
            el.addEventListener(el.$type, el.$handle, immediate);
        },
        unmounted(el: any) {
            el.removeEventListener(el.$type, el.$handle);
        }
    })
}
// 使用 在main.ts 中導入
import { direcitiveFUc } from './directives/index'
const app = createApp(App);
direcitiveFUc(app)
app.mount('#app');
 
//頁面使用 列:<a-button v-debounce="[test,'click',1000,true]">防抖測試</a-button>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM