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

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打进日志。

以上。

猜你喜欢

转载自www.cnblogs.com/foxcharon/p/10241580.html