vue-day12--监听属性

发布时间 2023-07-09 22:03:41作者: 雪落无痕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>
<!--
监视属性watch
1.当被监视的属性发生变化的时候,回调函数自动调用进行相关操作
2.监视的属性必须存在才能进行监视
3.监视属性的二种写法
1)new Vue 时传入watch 配置
2)通过vm.$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调用一下
// //handler 什么时间调用 当ishot发生变化的时候
// handler(newValue, oldValue) {
// console.log("ishot发生了变化", newValue, oldValue);
// },
// },
// },
});

vm.$watch("ishot", {
immediate: true, //初始化的时候让handler调用一下
//handler 什么时间调用 当ishot发生变化的时候
handler(newValue, oldValue) {
console.log("ishot发生了变化", newValue, oldValue);
},
});
</script>
</html>