vue3中,watch对象全部属性的时候,存在一个暂时无解问题:获取不到old数据
let book= reactive ({
name: 'JavaScript高级程序设计',
publish_time: 2022
})
watch(book, (newValue, oldValue) => {
console.log('book---', newValue, oldValue)
})
// 获取不到oldValue, 输出的都是新数据
vue3可同时监听多个值
let value1 = ref('hello')
let value2 = ref('javascript')
watch([value1, value2], (newValue, oldValue => {
console.log(newValue, oldValue)
})
watch对象中的某个属性
let book= reactive ({
name: 'JavaScript高级程序设计',
publish_time: 2022
})
watch(() => book.name, (newValue, oldValue => {
console.log(newValue, oldValue)
})
watch对象中的多个属性
let book= reactive ({
name: 'JavaScript高级程序设计',
publish_time: 2022
})
watch([() => book.name, () => book.publish_time], (newValue, oldValue => {
console.log(newValue, oldValue)
})
如果watch对象里面的对象的属性,需要deep: true
let book= reactive ({
name: 'JavaScript高级程序设计',
publish_time: 2022,
value: {
obj: {
age: 18
}
}
})
watch(() => book.value, (newValue, oldValue => {
console.log(newValue, oldValue)
}, {deep: true})
// 也不能获取到oldValue
watchEffect 不需要指定watch哪个,里面用到了哪个属性就会监听哪个属性,有点类似于vue2中的computed,某个值变化了就会执行
let age = ref(18)
let name = ref('凹凸曼')
let school = ref('中学')
watchEffect(() => {
const a = age.value
const n = name.value
console.log('change-----')
})
// 只要name或者age变化了,watchEffect就会响应,但是school变化了不会执行
网友评论