-最近在使用vue3.0编写项目,watch这个事件和2.0使用方式还是有一些差距,记录一下,便于以后学习
const state = reactive({count:1})
监听一个reactive定义的数据
watch(() => state.count,(newCount,oldCount) =>{
console.log(newCount,'新数据源')
console.log(oldCount,'老数据源')
})
const num = ref(0)
监听一个ref
watch(num,(newNum,oldNew) =>{
console.log(newNum,'新数据源')
console.log(oldNew,'老数据源')
})
监听多个数据源
const state = reactive({count:1})
const num = ref(0)
watch([()=> state.count,num],([newCount,newNum],[oldCount,newOld])=>{
console.log('new:',newCount,newNum);
console.log('old:',oldCount,oldNum);
})
监听复杂对象
const state = reactive({
person: {
name: '张三',
fav: ['帅哥','美女','音乐']
},
});
watch(() => state.person,(newPerson,oldPerson) =>{
console.log("新值:", newType, "老值:", oldType);
},{
deep:true //立即监听
})