* 創建一個自定義的 ref,并對其依賴項跟蹤和更新觸發進行顯式控制。
* 需求: 使用 customRef 實現 debounce 的示例。
**示例1:`ref`演示實時數據呈現**
```html
<template>
<!-- 2. 將input的value與keyword進行綁定 -->
<input type="text" v-model="keyword" />
<h3>{{ keyword }}</h3>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
//1. 創建一個ref響應式數據
const keyword = ref('abc')
return {
keyword,
}
},
})
</script>
```
效果如下,當改變 input 中的值時,界面是實時的更新數據的。

<br/>
**示例2:使用 customRef 實現 debounce 的示例**
```html
<template>
<!-- 3. 將input的value與keyword綁定 -->
<input type="text" v-model="keyword" />
<h3>{{ keyword }}</h3>
</template>
<script lang="ts">
import { customRef, defineComponent, ref } from 'vue'
//1. 調用 customRef 自定義hook防抖的函數
function useDebouncedRef < T > (value: T, delay = 200) {
//存儲定時器的id變量
let timeOutId: number
return customRef((track, trigger) => {
return {
get() {
//告訴vue追蹤數據
track()
return value
},
set(newValue: T) {
//清理定時器
clearTimeout(timeOutId)
//開啟定時器
timeOutId = setTimeout(() => {
value = newValue
//告訴vue更新界面
trigger()
}, delay)
},
}
})
}
export default defineComponent({
setup() {
//2. 調用自定義的hook函數
const keyword = useDebouncedRef('agc', 500)
return {
keyword,
}
},
})
</script>
```
效果如下,當改變 input 中的值時,界面需要等待指定的時間才顯示到界面上。

- nodejs
- 同時安裝多個node版本
- Vue3
- 創建Vue3項目
- 使用 vue-cli 創建
- 使用 vite 創建
- 常用的Composition API
- setup
- ref
- reactive
- 響應數據原理
- setup細節
- reactive與ref細節
- 計算屬性與監視
- 生命周期函數
- toRefs
- 其它的Composition API
- shallowReactive與shallowRef
- readonly與shallowReadonly
- toRaw與markRaw
- toRef
- customRef
- provide與inject
- 響應式數據的判斷
- 組件
- Fragment片斷
- Teleport瞬移
- Suspense
- ES6
- Promise對象
- Promise作用
- 狀態與過程
- 基本使用
- 常用API
- async與await
- Axios