天气案例(点击按钮可切换其他页面)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<!--
1.需求:点击button标签,可以来回切换“炎热”,“寒冬”
两种写法:
插值 <h1>今日天气{{inhot ? '炎热' : '寒冬'}}</h1> 三元表达式
计算属性 info(){
return this.a ? '炎热' : '寒冷'
}

事件监控
2.需求:点击button标签,来回切换“炎热和寒冬”后,控制台打印出事件监控,点击的事件
作用:
1.监控属性变化时,回调函数自动调用(newValue,oldValue)
2.监控属性必须存在,才能进行监视
3.两种写法:(new vue时传入watch配置) (通过vm.$swatch监视)
// watch:{
// inhot:{
// immediate:true, //将默认值输出出来
// handler(newValue,oldValue) {
// console.log('值被修改了',newValue,oldValue)
// }
// },
// },
2. vm.$watch('inhot',{
immediate:true,
handler(newValue,oldValue){
console.log('打印出来值',newValue,oldValue)
}
})

-->
<script type="text/javascript" src="./vue.js"></script>
</head>
<body>
<div id="root">
<h1>今日天气{{info}}</h1>
<button @click='changeWeather'>预报</button>

</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false

const vm = new Vue ({
el:'#root',
data:{
inhot:true, //开关,true,false
number:{
a:1,
b:1
}
},
computed:{
info(){
return this.inhot ? '炎热' : '寒冷'//true=炎热,false=寒冬
}
},
methods:{
changeWeather(){
this.inhot = !this.inhot//两级反转 比如当前是炎热,点击button=寒冬
}
},

watch:{
// inhot:{
// immediate:true, //将默认值输出出来
// handler(newValue,oldValue) {
// console.log('值被修改了',newValue,oldValue)
// }
// },
// 简写
// inhot:{
// handler(newValue,oldValue){
// console.log('值被修改了',newValue,oldValue)
// }
// }
},
})
// vm.$watch('inhot',{
// immediate:true,
// handler(newValue,oldValue){
// console.log('打印出来值',newValue,oldValue)
// }
// })
//简写
vm.$watch('inhot', function(newValue,oldValue){
console.log('222',newValue,oldValue)
})

</script>

</html>

posted on 2022-10-31 09:39  爱前端的小魏  阅读(44)  评论(0编辑  收藏  举报

导航