vue--day12--深度监视

发布时间 2023-07-09 22:34:07作者: 雪落无痕1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>天气案例--监听属性</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!--
深度监视
1.vue 中的watch 默认不监测对象内部值的变化(一层)
2.配置deep:true 可以监测对象内部值的改变(多层)
备注
1.vue 自身可以监测对象内部值的改变,但是vue提供的watch默认不可以
2.使用watch时更具数据的具体机构,决定是否采用深度监视
-->
<div id="root">
<div>欢迎来带{{name}}学习</div>

<h1>今天天气很{{info}}</h1>
<button @click="changeweather">切换天气</button>
<h3>a的值是{{numbers.a}}</h3>
<button @click="numbers.a++">点我让a+1</button>
<h3>1的值是{{numbers.b}}</h3>
<button @click="numbers.b++">点我让b+1</button>
</div>
</body>

<script type="text/javascript">
const vm = new Vue({
el: "#root",
data: {
name: "尚硅谷",
ishot: true,
numbers: {
a: 1,
b: 1,
},
},
methods: {
changeweather() {
this.ishot = !this.ishot;
},
},
computed: {
info() {
return this.ishot ? "炎热" : "凉爽";
},
},

watch: {
ishot: {
immediate: true, //初始化的时候让handler调用一下
//handler 什么时间调用 当ishot发生变化的时候
handler(newValue, oldValue) {
console.log("ishot发生了变化", newValue, oldValue);
},
},
//监视多级结构中的某个属性的变化
// "numbers.a": {
// handler(newValue, oldValue) {
// console.log("a发生了变化", newValue, oldValue);
// },
// },
//监视多级结构中所有的属性的变化
numbers: {
deep: true,
handler(newValue, oldValue) {
console.log("numbers发生了变化", newValue, oldValue);
},
},
},
});
</script>
</html>