vue中computed和watch的使用实例代码解析

需求:

  • 1.点击按钮实现天气的切换;
  • 2.用watch进行监视天气产生变化的数据;

实现代码(helloworld.vue实现代码):

<template>
 <!-- 准备好一个容器-->
		<div id="root">
			<h2>今天天气很{{info}}</h2>
			<button @click="changeWeather">切换天气</button>
		</div>
</template>
 
<script>
export default {
  name:'HelloWorld',
  data(){
    return{
      isHot:true,
    }
  },
  computed:{
    info(){
      return this.isHot ? '炎热' : '凉爽'
  methods: {
				changeWeather(){
					this.isHot = !this.isHot
				}
			},
  watch:{
    isHot(val){
      console.log("isHot被修改了,isHot值为:",val)
  }
}
</script>
<style>
</style>

注意:watch监听的对象都是在data()中已经定义好的数据。

本文转自网络,如有侵权请联系客服删除。