watchEffect

立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数。

用法

let message = ref<string>('')
let message2 = ref<string>('')
 watchEffect(() => {
    console.log('message', message.value);
    console.log('message2', message2.value);
    // 同时监听message 和 message2
})

清除副作用

import { watchEffect, ref } from 'vue'
let message = ref<string>('')
let message2 = ref<string>('')
 watchEffect((oninvalidate) => {
    oninvalidate(()=>{
      // 监听函数前调用,可用于防抖等逻辑
    })
    console.log('message2', message2.value);
})

停止监听

watchEffect 本身会返回一个函数,调用后将停止监听

const stop =  watchEffect((oninvalidate) => {
    console.log('message2', message2.value);
},{
    flush:"post",
    onTrigger () {
      // 监听触发时调用,可用于代码调试
    }
})
stop() // 调用后将不再监听

副作用刷新时机 flush

一般使用post

presyncpost
更新时机组件更新前执行强制效果始终同时触发组件更新后触发
Last Updated:
Contributors: haizhiguang