How to use this.$set(), detailed teaching (the wonderful use of this.$set() in the vue project)

1. Objects use this.$set() to modify and add:

obj: { name: "Xiao Ming", age: 18, }, //object

eg: this.$set(object that needs to be changed, "object attribute that needs to be changed", "new value")

1. Object modification

this.$set(this.obj, "name", "小刘"); 
//控制台输出:obj: { name: "小刘", age: 18, },

2. Add new objects

this.$set(this.obj, "hobby", "study");
//控制台输出:obj: { name: "小明", age: 18, hobby: "study"},  

3. The new object is unknown (the item here is the parameter passed without quotation marks , and "reading" is the parameter value)


this.$set(this.obj, item, "reading");

2. Use this.$set() to modify and add arrays:

arr: [ //Array object

  { name: "小王", age: 18 },

  { name: "Xiao Zhang", age: 20 },

 ],       

twoArr: [11, 22, 33, ], //ordinary array

eg: this.$set (array that needs to be modified, array subscript that needs to be modified, { "array object to be modified, one/multiple" })

1. Array modification

数组对象:
this.$set(this.arr, 1, { name: "小王", age: 19 });          
//控制台输出:arr: [ { name: "小王", age: 18 },{ name: "小王", age: 19 }, ],
普通数组:
this.$set(this.twoArr, 0, 99);       
//控制台输出:twoArr: [99, 22, 33, ],   

2. Added array

(1) First get the length of the array that needs to be added:

let reslg = this.arr.length;  

(2) Then add at the end of the array:

this.$set(this.arr, reslg,{ name: "小紫", age: 18 },);
//控制台输出:
    arr: [ 
        { name: "小王", age: 18 },
        { name: "小张", age: 20 },
        { name: "小紫", age: 18 },
        ],

In the same way, you can use this when the array or object is not updated when deleting:

this.$delete(this.obj, "name")

Supplement: Pay attention to the use of quotation marks! ! ! ! ! !

Guess you like

Origin blog.csdn.net/weixin_65793170/article/details/127869019