立即运行一个函数,同时响应地跟踪它的依赖关系,并在依赖关系发生变化时重新运行它。
类型
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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。