vue中watch实际上是用来监听vue实例中的数据变化
监听String
<template>
<div @click="stringClick">{{msg}}</div>
</template>
<script>
export default {
name: "jianting",
data() {
return {
msg: "1223"
};
},
watch: {
msg: function(newVal, oldVal) {
// TO DO
("newVal:", newVal);
("oldVal:", oldVal);
}
},
methods: {
stringClick() {
= () * 100;
}
}
};
</script>
监听对象
<template>
<div @click="click">
<div>姓名:{{}},年龄:{{}},他的儿女有:</div>
<div v-for="(item, index) in " :key="index">姓名:{{}},年龄:{{}}</div>
</div>
</template>
<script>
export default {
name: "jianting",
data() {
return {
obj: {
name: "Tony",
age: 50,
children: [
{
name: "小明",
age: 12
},
{
name: "小花",
age: 5
}
]
}
};
},
watch: {
obj: {
handler: function(newVal, oldVal) {
// TO DO
("newVal:", newVal);
("oldVal:", oldVal);
},
deep: true,
immediate: true
},
"": function(newVal, oldVal) {
// TO DO
("newVal :", newVal);
("oldVal :", oldVal);
}
},
methods: {
click() {
= "未知";
}
}
};
</script>
watch监听对象的时候,需要加deep:true,只有这样才能深入底层去实时监听,没有加的话,对象是监听不到变化的,添加immediate时会在侦听开始之后被立即调用
监听路由
watch: {
$route: {
handler: function(val, oldVal) {
(val);
},
// 深度观察监听
deep: true,
immediate: true
}
}