官方文件連結:https://vueuse.org/shared/useThrottleFn/
今天就從 useThrottleFn 開始吧!核心基本上就是熟悉的那個 throttle,再加上一些有的沒的(不是
vueuse 原始碼檔案:https://github.com/vueuse/vueuse/blob/main/packages/shared/useThrottleFn/index.ts
// src/compositions/useThrottleFn.js
import { throttleFilter } from '@/utils/filter'
export function useThrottleFn(fn, ms) {
return throttleFilter(fn, ms)
}
vueuse 原始碼檔案:https://github.com/vueuse/vueuse/blob/main/packages/shared/utils/filters.ts#L147
// src/utils/filter.js
export function throttleFilter(fn, ms) {
return fn
}
vueuse 原始碼檔案:https://github.com/vueuse/vueuse/blob/main/packages/shared/useThrottleFn/demo.vue
<!-- src/components/UseThrottleFnDemo.vue -->
<script setup>
import { ref } from 'vue'
import { useThrottleFn } from '@/compositions/useThrottleFn'
const clicked = ref(0)
const updated = ref(0)
const throttledFn = useThrottleFn(() => {
updated.value += 1
})
function clickHandler() {
clicked.value += 1
throttledFn()
}
</script>
<template>
<h2>UseThrottleFnDemo</h2>
<div class="box" @click="clickHandler">
<span>click throttle box</span>
</div>
<div>Button clicked: {{ clicked }}</div>
<div>Event handler called: {{ updated }}</div>
</template>
<style>
.box {
width: 300px;
height: 300px;
background: #ccc;
}
</style>
接下來會從最基本的 throttle 功能開始實作,核心邏輯會寫在 throttleFilter 這個 function,在這邊陸續把功能補齊。
GitHub:https://github.com/RhinoLee/30days_vue/pull/4/files