vue-day12-监视属性简写

发布时间 2023-07-09 22:59:29作者: 雪落无痕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>
</div>
</body>

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

watch: {
//正常的写法
// ishot: {
// // immediate: true, //初始化的时候让handler调用一下
// // deep:true,//深度监视
// //handler 什么时间调用 当ishot发生变化的时候
// handler(newValue, oldValue) {
// console.log("ishot发生了变化", newValue, oldValue);
// },
// },
//简写
// ishot(newValue, oldValue) {
// console.log("ishot发生了变化", newValue, oldValue);
// },
},
});

//正常的写法
// vm.$watch("ishot", {
// // immediate: true, //初始化的时候让handler调用一下
// // deep:true,//深度监视
// //handler 什么时间调用 当ishot发生变化的时候
// handler(newValue, oldValue) {
// console.log("ishot发生了变化", newValue, oldValue);
// },
// });

//简写
vm.$watch("ishot", function (newValue, oldValue) {
console.log("ishot发生了变化", newValue, oldValue);
});
</script>
</html>