# 自定义ref 可以在响应式的逻辑过程中添加逻辑
import { customRef } from '@vue/reactivity' export default { name: 'Demo', setup(){ function myRef(value){ return customRef((track,trigger)=>{ return { get(){ track() return value }, set(newValue){ setTimeout(()=>{ value = newValue trigger() },500) } } }) } let keyword = myRef('hello') return { keyword } } }
# 防抖 ,可以通过每次开启定时器之前先清除之前的定时器
<script> import { customRef } from '@vue/reactivity' export default { name: 'Demo', setup(){ function myRef(value){ let timer return customRef((track,trigger)=>{ return { get(){ track() # 追踪数据 return value }, set(newValue){ clearTimeout(timer) timer = setTimeout(()=>{ value = newValue trigger() # 重新解析模板 },500) } } }) } let keyword = myRef('hello') return { keyword } } }