<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="../../../js/vue.js"></script>
<title>天气案例</title>
</head>
<body>
<div id="root">
<h2>今天天气很{{info}}</h2>
<!--
1.@xxx="yyy" yyy可以写一些简单的语句
2. <button @click="isHot = !isHot">切换天气</button>
-->
<button @click="changeWeather">切换天气</button>
</div>
</body>
<script>
const vm = new Vue({
el:'#root',
data:{
isHot:true
},
computed:{
info(){
return this.isHot ? '炎热':'凉爽'
}
},
methods: {
changeWeather(){
this.isHot = !this.isHot
}
}
// watch:{
// isHot:{
// immediate:true,
// //handler什么时候调用?当isHot发生改变时
// handler(newValue,oldValue){
// console.log('isHot被修改了',newValue,oldValue)
// }
// }
// }
})
vm.$watch('isHot',{
immediate:true,
handler(newValue,oldValue){
console.log(isHot被修改了,newValue,oldValue)
}
})
</script>
<!--
1.监视属性:
1.当监视的属性变化时,回调函数自动调用,进行相关操作
2.监视的属性必须存在,才能进行监视
3.监视的两种写法:
(1). new Vue时传入watch配置
(2). 通过vm.$watch监视
-->
</html>
Vue中的数据监视(Watch)
最新推荐文章于 2024-05-16 21:56:24 发布
该代码示例展示了如何使用Vue.js创建一个简单的天气应用,动态显示天气信息(炎热或凉爽),并提供按钮切换天气状态。数据绑定、计算属性和方法用于更新界面,同时有注释介绍了$watch的使用来监听isHot属性的变化。
摘要由CSDN通过智能技术生成