The method of monitoring and re responding to the change of array value in vue

Posted by xexmple on Mon, 23 Dec 2019 19:14:12 +0100

During the development of our project, the data types in the instance can be objects, arrays, etc. In the object, when a property value changes, we can monitor the depth of the object to achieve the requirement of re rendering the page. Or check out the blogger's article https://blog.csdn.net/weixin_37861326/article/details/81034231

For example:

<script>
  export default {
    data(){
      return {
        objVal: {
          name: 'obj',
          type: 'obj'
        }
      }
    },
    watch:{
      objVal:{
        handler(val,oldval){

        },
        deep: true,
      }
    },
    methods:{
      changeObj(){
        this.objVal.name = 'newobj';
      }
    }
  }
</script>

However, this is not valid when listening for array value changes in the same way.

<script>
export default {
  data() {
    return {
      arrList: [1,2,3,4,5]
    };
  },
  watch: {
    arrList: {
      handler(val, oldval) {

      },
      deep: true
    }
  },
  methods: {
    changeArr() {
      // invalid
      this.arrList[0] = 10;
    }
  }
};
</script>

The above method for monitoring array value changes is invalid. vue will not re render the page in response to data changes. In vue, only by modifying the assignment statement, the vue can respond to the changes of array data. The specific operations are as follows:

usage method:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)

Specific use cases:

<script>
export default {
  data() {
    return {
      arrList: [1,2,3,4,5]
    };
  },
  methods: {
    changeArr() {
      // this.arrList[0] = 10;
      // Revised to:
      this.arrList.splice(0, 1, 10);
    }
  }
};
</script>

Or:

<script>
export default {
  data() {
    return {
      arrList: [1,2,3,4,5]
    };
  },
  methods: {
    changeArr() {
      // this.arrList[0] = 10;
      // Revised to:
      this.$set(this.arrList, 0, 10);
    }
  }
};
</script>

The above two methods can achieve the effect of monitoring array value changes.

Topics: Vue