码迷,mamicode.com
首页 > 编程语言 > 详细

vue : watch、computed、以及对象数组

时间:2019-01-08 21:57:19      阅读:429      评论:0      收藏:0      [点我收藏+]

标签:submit   数组   com   特性   计算属性   框架   重要   绑定   console   

watch和computed是vue框架中很重要的特性。

那么,他们是怎么作用于对象数组的?

今天我们就来探究一下。

 

上代码。

<template>
  <div class="hello">
    {{ msg }} 
    
    <div>
      <button @click="submit">plus</button>
    </div>
    
    <div>{{ testNum }}</div>
  </div>
</template>

<script>

export default {
  name: abc,
  data () {
    return {
      msg: Welcome to Your Vue.js App,
      originNum:0,
      originObj:[

      ]
     
    }
  },
  
  computed: {    
    testNum(){
      console.log("computed")
      if (this.originObj.length === 0) {
        this.$set(this.originObj, 0, {number:0})
        return this.originObj[0].number
      }      
      let obj = this.originObj[0]
      obj.number = -obj.number
      this.$set(this.originObj, 0, obj)
      
      return this.originObj[0].number
    }
  },
  watch:{
    originObj:{
      handler: function (val, oldVal) { console.log("watch") },
      deep:true
    }
  },
  created(){
    
  },
  mounted(){
    
  },  
  methods:{
    submit(){
      let obj = this.originObj[0]
      obj.number = 100
      this.$set(this.originObj, 0, obj)
    }
  }
};
</script>


<style scoped>

</style>

 

首先是初始化(进入这个页面时)。

技术分享图片

从日志中可以看到,先调用了computed,再调用了watch。

看代码。数据绑定是绑定了computed:testNum,所以初始化时就会调用。

      if (this.originObj.length === 0) {
        this.$set(this.originObj, 0, {number:0})
        return this.originObj[0].number
      }   

因为初始的对象数组originObj没有对象,所以加了一个对象。watch监听到originObj改变了,所以打了日志。

    submit(){
      let obj = this.originObj[0]
      obj.number = 100
      this.$set(this.originObj, 0, obj)
    }

然后,我点击按钮,触发submit()方法。

 

技术分享图片

再看日志,分别触发了watch computed watch。

submit()方法修改了this.originObj[0].number,this.originObj的watch加了deep:true,所以可以监听到,watch打进日志。

this.originObj改变了,所以触发了computed:testNum(计算属性computed有缓存,只在值改变时触发),computed打进日志。

computed:testNum触发的时候同时也修改了this.originObj,所以再次触发watch,watch打进日志。

 

以上。

vue : watch、computed、以及对象数组

标签:submit   数组   com   特性   计算属性   框架   重要   绑定   console   

原文地址:https://www.cnblogs.com/foxcharon/p/10241580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!