zoukankan      html  css  js  c++  java
  • 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打进日志。

    以上。

  • 相关阅读:
    UINavigationController
    UIWebView
    控制器view的加载顺序initWithNibName >>> viewDidLoad >>> viewWillAppear >>> viewDidAppear
    UITableView
    JS调用OC方法
    【概念】winform的特点
    【概念】指针
    【c++】类的继承(三种继承方式)、基类和派生类、面向对象三要素
    【笔试】C++笔试题
    【c#】解决DataTable.Rows.Add(dr)语句执行速度慢的问题(GridControl)
  • 原文地址:https://www.cnblogs.com/foxcharon/p/10241580.html
Copyright © 2011-2022 走看看