## VUE3.0 ### watchEffect * watchEffect 默认进入页面立即执行 ``` setup() { // watchEffect: 自动收集响应式的依赖 const name = ref("why"); const age = ref(18); const changeName = () => name.value = "kobe" const changeAge = () => age.value++ watchEffect(() => { console.log("name:", name.value, "age:", age.value); }); return { name, age, changeName, changeAge } } ``` * 停止侦听 ``` const stop = watchEffect(() => { console.log("name:", name.value, "age:", age.value); }); stop(); //调用stop()方法停止侦听 ``` * 执行时机 flush `post` `pre` `sync` 默认 pre ``` watchEffect(() => { console.log(title.value); }, { flush: "post" }) ``` ### watch ``` setup() { const info = reactive({name: "why", age: 18}); // 1.侦听watch时,传入一个getter函数 watch(() => info.name, (newValue, oldValue) => { console.log("newValue:", newValue, "oldValue:", oldValue); }) // 2.传入一个可响应式对象: reactive对象/ref对象 // 情况一: reactive对象获取到的newValue和oldValue本身都是reactive对象 watch(info, (newValue, oldValue) => { console.log("newValue:", newValue, "oldValue:", oldValue); }) // 如果希望newValue和oldValue是一个普通的对象 watch(() => { return {...info} }, (newValue, oldValue) => { console.log("newValue:", newValue, "oldValue:", oldValue); }) // 情况二: ref对象获取newValue和oldValue是value值的本身 const name = ref("why"); watch(name, (newValue, oldValue) => { console.log("newValue:", newValue, "oldValue:", oldValue); }) const changeData = () => { info.name = "kobe"; } return { changeData, info } } ```