Vue3只能监视以下4种数据
- ref定义的数据
- reactive定义的数据
- 函数返回的一个值(getter函数)
- 一个包含上述内容的数组
场景
- 监视ref基本类型
import { ref,watch } from 'vue'
let sum = ref(0)
function changeSum() {
sum.value = sum.value + 1
}
let stopWatch = watch(sum, (newValue, oldValue) => {
console.log(oldValue, newValue)
if (newValue > 10) {
stopWatch() //停止监视
}
})
2.ref监视 对象类型数据
let person = ref({
name: '张三',
age: 18
})
function ageAdd() {
person.value.age++
}
function changePerson() {
person.value = {
name: '李四',
age: 20
}
}
watch(person, (newValue, oldValue) => { //这里监视的是对象的地址值的变化,整个对象都发生了变化
console.log(oldValue, newValue)
console.log('person被修改了')
})
watch(person, (newValue, oldValue) => {
console.log(oldValue, newValue)
console.log('person被修改了')
},{deep: true})//深度监视,对象里面的m 的属性被修改了也监视
//还有一个选项immediate: true,立即执行一次,界面加载就执行
3.reative类型数据
let person = reactive({
name: '张三',
age: 18
})
function ageAdd() {
person.age++
}
function changePerson() {
person = Object.assign(person,{name:'王五',age:20})
}
watch(person,(newPerson,oldPerson)=>{ //reactive默认开启深度监视
console.log('new',newPerson)
console.log('old',oldPerson)
})