This time I will bring you the assignment problem of vuearray and object. What are the notes of vue array and object assignment, as follows This is a practical case, let’s take a look at it.
Vue cannot detect the following changed arrays:
When you set an item directly using the index, for example: vm.items[indexOfItem] = newValue
When you modify the length of the array, for example: vm.items.length = newLength
When required in the first case, you can use this.$set(this.arr,index,newVal)
Vue cannot detect the addition or deletion of the object attribute :
You can use this.$set(this.person,'age',12)
When you need to add multiple objects, <a href="http://www.php.cn/wiki/60.html" target="_blank">Object</a>.assign({},this.person,{age:12,name:'wee'})
PS: Vue implements deep copy and replication of arrays and objects
When an object is passed between components, since the reference type of this object all points to an address (except for the basic type and null, the assignment between objects only points the address to the same one, not in the true sense copy), as follows
Array:
var a = [1,2,3]; var b = a; b.push(4); // b中添加了一个4 alert(a); // a变成了[1,2,3,4]
Object:
var obj = {a:10}; var obj2 = obj; obj2.a = 20; // obj2.a改变了, alert(obj.a); // 20,obj的a跟着改变
This is due to the direct assignment of the object type, which just points the reference to the same address. Modifying obj will also cause obj2 to be modified
So in Vue, if multiple components reference the same object as data, then when one of the components changes the object data, the data of other objects will also be changed simultaneously. If there is a need for such two-way binding, then it is naturally the best. But if you do not need this binding and want the object data of each component to be independent of each other, that is, copies of objects that are not related to each other, you can use the following Solution
computed: { data: function () { var obj={}; obj=JSON.parse(JSON.stringify(this.templateData)); //this.templateData是父组件传递的对象 return obj } }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How does Yuansheng JS implement asynchronous file upload
js performs time size comparison
The above is the detailed content of Assignment issues between vue arrays and objects. For more information, please follow other related articles on the PHP Chinese website!