直接看下面代碼:
1.紅色的的為一個對象,watch監聽時。需要借助 computed 屬性,否則watch監聽打印出來的新舊值看不出。(注:方法可以隨便寫,但是 computed 中 與 watch的名字要一致,且computed中必須return返回值。)
2.藍色的的為一個普通的變量,watch監聽獲取它的新舊值時,直接在watch中書寫即可。(注:名字必須為 要監聽的 變量名字)
data(){ return{ Form:{aaa: '',bbb:''}, value: '', } } computed: { NewForm() { return JSON.parse(JSON.stringify(this.Form)); }, }, watch: { NewForm: { handler(newVal, oldVal) { console.log('舊值:',oldVal); console.log('新值:',newVal); }, deep: true, //深度監聽(可監聽到對象、數組的變化) }, value(newVal,oldVal) { console.log('舊值:',oldVal); console.log('新值:',newVal); } }