- 两者都可监听 data 属性变化
- watch 需要明确出要被监听的属性
- watchEffect 会根据其中的属性,自动监听其变化
<template>
<p>watch watchEffect</p>
<p>{{numRef}}</p>
<p>{{name}} {{age}}</p>
</template>
<script>
import { reactive, ref, toRefs, watch } from 'vue';
export default {
name: 'watch',
setup() {
const numRef = ref(100);
const state = reactive({
name: "zwx",
age: 26
})
watch(numRef, (newNum, oldNum) => console.log('监听到了watch的变化', newNum, oldNum), {
immediate: true // 初始化即监听
})
// setTimeout(() => {
// numRef.value = 101
// }, 1000)
watch(
// 确定要监听的属性
() => state.age,
(newStateAge, oldStateAge) => {
console.log('state watch', newStateAge, oldStateAge)
},
{
immediate: false,
deep: false // 深度监听
}
)
setTimeout(() => {
state.age = 27;
}, 1000)
setTimeout(() => {
state.name = 'pw';
}, 3000)
return {
numRef,
...toRefs(state)
}
}
}
</script>
// 初始化时 一定会执行一次 (原因:收集要监听的数据)
watchEffect(() => {
console.log('hello')
})
watchEffect(() => { // 初始化和在 state.name 改变时会触发
console.log('state.name', state.name)
})