1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
实际开发中,watch会随着组件一并销毁。
</div>
</body>

<script>
var app = new Vue({
el: '#app',
data: {
vall: 'val1',
val2: 'val2',
val3: 'val3',
val4: 'val4',
val5:{
a:'a'
},
val6:{
a:'a'
}
},
watch: {
vall(newName){
console.log('一个参数');
console.log("新值val1:" + newName)
},
val2(newName, oldName) {
console.log('两个参数');
console.log("新值val2:" + newName);
console.log("旧值val2:" + oldName)
},
val3: {
handler(newName) {
console.log('handler 一个参数');
console.log("新值val3:" + newName);
},
// 代表在wacth里声明了val3这个方法之后立即先去执行handler方法,
// 如果设置了false,那么效果和上边例子一样
// 如果设置了true,启动时就会执行一次handler
immediate: true
},
val4: {
handler(newName, oldName) {
console.log('handler 两个参数');
console.log("新值val4:" + newName);
console.log("旧值val4:" + oldName)
},
immediate: true
},
val5: {
handler(newName, oldName) {
console.log('val5.a changed');
console.log('val5.a = ' + newName);
},
immediate: true,
// val5.a发生变化会监测到
deep: true
},
'val6.a': { // 建议使用该方法,不要使用val5的方法
handler(newName, oldName) {
console.log('val6.a changed');
console.log('val6.a = ' + newName);
},
immediate: true,
}
}
});
</script>


<style>
html, body {
margin: 5px;
padding: 0;
}
</style>
</html>