Vue2.0 object adds new attribute methods $set, object.assign()

A problem often encountered in projects in vue2.0 is to add new properties to objects, but the view does not update the problem.

1. Example:

Step 1: Initialize an object obj in data: { name : 'Zhang San' };

data(){
    return{
        obj:{
			name:'张三'
        },
    }
}

Step 2: Use v-for to loop the object in the template and render the data;

//模板
<template>
  <div class="page-body">
      <p v-for="(value,key) in obj">{
   
   {key}}-----{
   
   {value}}</p>
      <button @click="addAge">添加age</button>
      </br>
      <button @click="delAge">删除age</button>
  </div>
</template>

Step 3: Click the Add button to add the age attribute; click the Delete button to delete the age attribute;

created(){
	console.log(this.obj);      // {name:'张三'}
},
methods:{
	addAge(){
		this.obj.age = 15;
		console.log(this.obj);  // {age:15, name:'张三'}
    },
    delAge(){
		delete this.obj.age;
		console.log(this.obj);  // {age:15, name:'张三'}
    },
}

2. Phenomenon:

When the Add button is clicked, the console outputs { age:15, name: 'Zhang San' }; but the page does not change; when the Delete button is clicked, the console outputs { name: 'Zhang San' }, and the page does not change ;

3. Analysis:

The reason is that vue cannot detect the addition or deletion of new properties of objects.

We all know that the two-way data binding of vue2.0 uses Object.defineProperty() to hijack the setter and getter of each property. When the data changes, it publishes a message to the subscriber, thereby triggering the corresponding monitoring callback.

Since obj.age was not declared when the vue instance was created, the property was not hijacked by Object.defineProperty(), and it was not converted into a responsive property, so when obj.age changes, the view update will not be triggered .

Fourth, the solution:

At this point, our protagonist is on the stage, that is vue.$set(), which can manually process obj.age into a responsive property, so that the view can be updated.

this.obj.age = 15 改成 this.$set( this.obj,'age',15 ) 

五、Object.assign()

        When you need to add multiple properties to an object, you can use Object.assign(target, obj1, obj2) to merge the objects. target is the merged object, obj1 and obj2 are the objects to be merged, when two objects have the same key, the later one will overwrite the former one.  

this.obj = Object.assign({},this.obj,{age:16,name:"张三"})

Note: object.assign is a shallow copy.

6. Array

        If you use index to modify an item in the array, such as this.arr[3] = 'lisi', this is also not responsive; you can also use the set method, this.$set( this.arr, 3, 'lisi' ) to modify the array.

おすすめ

転載: blog.csdn.net/Hello_MrShu/article/details/127320131