点击按钮。可以实现天气的直接切换。并且在控制台显示切换前后的天气
实现天气切换部分
直接写:使用三目运算符 但是过于麻烦使用计算属性
<!-- 准备容器 -->
<div id="root">
<!-- 但是过于麻烦使用计算属性 -->
<h2>今天天气很{{isHot ? '炎热':'凉爽'}}</h2>
<button>切换天气</button>
</div>
<script type="text/javascript">
new Vue({
el: '#root',
data: {
isHot: true,//使用布尔值进行两个判断
},
});
</script>
计算属性
<body>
<!-- 准备容器 -->
<div id="root">
<!-- 但是过于麻烦使用计算属性 -->
<h2>今天天气很{{info}}</h2>
<button>切换天气</button>
</div>
<script type="text/javascript">
new Vue({
el: '#root',
data: {
isHot: true,//使用布尔值进行两个判断
},
computed:{
info(){//返回值就是info的值,必须写this拿到该属性
return this.isHot ? '炎热':'凉爽'
}
}
});
</script>
</body>
实现按钮绑定事件
为事件对象绑定方法
<body>
<!-- 准备容器 -->
<div id="root">
<!-- 但是过于麻烦使用计算属性 -->
<h2>今天天气很{{info}}</h2>
<button @click="changeWeather">切换天气</button>
</div>
<script type="text/javascript">
new Vue({
el: '#root',
data: {
isHot: true,//使用布尔值进行两个判断
},
computed:{
info(){//返回值就是info的值,必须写this拿到该属性
return this.isHot ? '炎热':'凉爽'
}
},
methods: {//方法
changeWeather(){
this.isHot=!this.isHot
}
},
});
</script>
</body>
--当我们使用我模板中没有使用到计算属性和属性中的数据时候,但是在事件中对属性进行了操作,vue开发者工具中显示的内容会不进行变化,不会更新,但是实际上改了。用vm实例对象进行更新
![](https://img-blog.csdnimg.cn/img_convert/1f660aca82348602e647fa5e4af91d50.png)
![](https://img-blog.csdnimg.cn/img_convert/ba5226e697b765e8cf3d205493911fca.png)
简化点击实现(即绑定事件后面写简单的语句)
可以直接在事件后面写简单的语句(多个语句也可。但是不最好不要,并且不支持警告函数alert,先去原型对象上找,找不到就结束报错。需要弹窗可以在vm对象上直接写一个
<body>
<!-- 准备容器 -->
<div id="root">
<!-- 但是过于麻烦使用计算属性 -->
<h2>今天天气很{{info}}</h2>
<button @click="isHot=!isHot">切换天气</button>
</div>
<script type="text/javascript">
const v= new Vue({
el: '#root',
data: {
isHot: true,//使用布尔值进行两个判断
},
computed:{
info(){//返回值就是info的值,必须写this拿到该属性
return this.isHot ? '炎热':'凉爽'
}
},
methods: {//方法
// changeWeather(){
// this.isHot=!this.isHot
// }
},
});
</script>
</body>
![](https://img-blog.csdnimg.cn/img_convert/e2ad9564a09d63e6c9428ceeb3c51f3e.png)
![](https://img-blog.csdnimg.cn/img_convert/c6abe4ffca4c659b8418825d8323b652.png)