VUE3.0

注:在vue2.6中data可作为一个对象 ,在VUE3.0中data只能作为一个函数

watch监视器事件

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
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/3.2.47/vue.global.prod.js"></script>
<style>
#app div,h1{
margin: 40px auto;
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<h1>watch监听简单数据类型</h1>
<div class="example1">
千米:<input type="text" v-model.number.lazy="kilo"/>
<=>
米:<input type="text" v-model.number.lazy="meter"/>
<p>左输入框修改前为:{{oldKilo}} ,修改后为:{{newKilo}}</p>
<p>右输入框修改前为:{{oldMeter}},修改后为:{{newMeter}}</p>
</div>
<h1>watch深度监听</h1>
<div class="example2">
用户名:<input type="text" v-model.lazy="user.name"/>
年龄:<input type="text" v-model.lazy="user.age"/>
</div>
</div>
<script>
const app=Vue.createApp({
data(){
return {
kilo:0,
meter:0,
oldKilo:0,
newKilo:0,
oldMeter:0,
newMeter:0,
user:{
name:"PuJunming",
age:22
}
}
},
watch:{
kilo(newVal,oldVal){
this.oldKilo = oldVal;
this.newKilo = newVal;
this.meter = newVal*1000;
},
meter(newVal,oldVal){
this.oldMeter = oldVal;
this.newMeter = newVal;
this.kilo = newVal/1000;
},
// 无法对对象进行深度监听 无法监听到对象的属性变化 无法监听到数组的变化
// user(newVal,oldVal){
// console.log("newVal:",newVal);
// console.log("oldVal:",oldVal);
// }

// "user.age"(newVal,oldVal){
// console.log("新user.age变化了"+newVal);
// console.log("旧user.age变化了"+oldVal);
// },
// "user.name"(newVal,oldVal){
// console.log("新user.name变化了"+newVal);
// console.log("旧user.name变化了"+oldVal);
// }

user:{
// handler 监听的回调函数
handler(newVal,oldVal){
console.log("new newVal:",newVal);
console.log("old oldVal:",oldVal);
},
// deep:true 深度监听 默认false 只能监听到一层
deep:true,
// immediate:true 立即执行一次 默认false 只有在值发生变化时才会执行
immediate:true
}
},
computed:{
newUser(){
return JSON.Parse(JSON.Stringify(this.user));
}
},
}).mount("#app");
</script>
</body>
</html>

监听属性