vue-computed与watch

例一:

 
//computed的计算属性的调用
<img :src="productIcon">

 <ul>
  <router-link v-for="item in products" :to="{ path: item.path }" tag="li" active-class="active">
    {{ item.name }}
  </router-link>
</ul>

<script>
export default {
  data () {
    return {
      products: [
        {
          name: '数据统计',
          path: 'count',
          icon: require('../assets/images/1.png'),
          active: false
        },
        {
          name: '数据预测',
          path: 'forecast',
          active: false
        },
        {
          name: '流量分析',
          path: 'analysis',
          active: false
        },
        {
          name: '广告发布',
          path: 'publish',
          active: false
        }
      ],

//路由映射
 imgMap: {
        '/detail/count': require("../assets/images/1.png"),
        '/detail/forecast': require("../assets/images/2.png"),
        '/detail/analysis': require("../assets/images/3.png"),
        '/detail/publish': require("../assets/images/4.png")
      }
    }
  },

//动态计算路由的变化
  computed: {
    productIcon () {
//this.$route.path获取页面的路由
 return this.imgMap[this.$route.path]
    }
  }
}

</script>

例二:


法一:通过计算属性监听
<div>
  <input type="text" v-model="myValue">
  <!--过滤掉“myValue”中的数字 “myValueWithoutNum”相当于data中的属性-->
  <span>







法二:通过methods里的方法监听

<div>
  <input type="text" v-model="myValue">
  <!--过滤掉“myValue”中的数字-->

  <span>{{getMyValueWithoutNum()}}</span>
</div>

methods:{
  getMyValueWithoutNum(){
    return this.myValue.replace(/\d/g,"");
  }

}
 

例三:用watch监听data里的变量,每当这个变量变动的时候,都会执行特定的操作


<ul>
  <li v-for="item in myList">{{item.name}}</li>
</ul>

<input type="text" v-model="myVal"> 

 watch:{
//它的key就是要监听的data里的属性
 myVal:function(newVal,oldVal){
   console.log(newVal,oldVal)
  },
  myList:function(){
    this.telluser();
  }
}


猜你喜欢

转载自blog.csdn.net/pansuyong/article/details/80587461