立即運行一個函數,同時響應地跟蹤它的依賴關係,並在依賴關係發生變化時重新運行它。
類型
function watchEffect(
effect: (onCleanup: OnCleanup) => void,
options?: WatchEffectOptions
): StopHandle
type OnCleanup = (cleanupFn: () => void) => void
interface WatchEffectOptions {
flush?: 'pre' | 'post' | 'sync' // default: 'pre'
onTrack?: (event: DebuggerEvent) => void
onTrigger?: (event: DebuggerEvent) => void
}
type StopHandle = () => void
細節
第一個參數是要運行的效果函數。效果函數接收可用於注冊清理回調的函數。清理回調將在下一次重新運行效果之前調用,可用於清理無效的副作用,例如待處理的異步請求(參見下麵的示例)。
第二個參數是一個可選的選項對象,可用於調整效果的刷新時間或調試效果的依賴關係。
返回值是一個句柄函數,可以調用它來阻止效果再次運行。
示例
const count = ref(0)
watchEffect(() => console.log(count.value))
// -> logs 0
count.value++
// -> logs 1
副作用清理:
watchEffect(async (onCleanup) => {
const { response, cancel } = doAsyncWork(id.value)
// `cancel` will be called if `id` changes
// so that previous pending request will be cancelled
// if not yet completed
onCleanup(cancel)
data.value = await response
})
停止觀察者:
const stop = watchEffect(() => {})
// when the watcher is no longer needed:
stop()
選項:
watchEffect(() => {}, {
flush: 'post',
onTrack(e) {
debugger
},
onTrigger(e) {
debugger
}
})
相關用法
- Vue.js watch()用法及代碼示例
- Vue.js watch用法及代碼示例
- Vue.js withDirectives()用法及代碼示例
- Vue.js withModifiers()用法及代碼示例
- Vue.js useSSRContext()用法及代碼示例
- Vue.js app.directive()用法及代碼示例
- Vue.js mergeProps()用法及代碼示例
- Vue.js app.config.warnHandler用法及代碼示例
- Vue.js pipeToWebWritable()用法及代碼示例
- Vue.js app.use()用法及代碼示例
- Vue.js v-pre用法及代碼示例
- Vue.js h()用法及代碼示例
- Vue.js serverPrefetch用法及代碼示例
- Vue.js customRef()用法及代碼示例
- Vue.js <Transition>用法及代碼示例
- Vue.js inject()用法及代碼示例
- Vue.js mixins用法及代碼示例
- Vue.js ComponentCustomProps用法及代碼示例
- Vue.js reactive()用法及代碼示例
- Vue.js ComponentCustomProperties用法及代碼示例
- Vue.js app.mount()用法及代碼示例
- Vue.js <component>用法及代碼示例
- Vue.js createRenderer()用法及代碼示例
- Vue.js onMounted()用法及代碼示例
- Vue.js createApp()用法及代碼示例
注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 watchEffect()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。