V-for binding array in VUE, when the array changes, the page data does not update the problem

  • Problem found:

 As shown in the figure, through the first Select selection, confirm the value of the second Select selection box. Since it is an incremental Form, a two-dimensional array is used to store the value of the second Select selection box. In the previous old method, the value returned by the interface was assigned through the subscript assignment method. It is found that there is no option, and when printing the log, it is found that there are values ​​in the array, why can't the page be displayed? Change the value of the first Select again, and find that the selection value of the second select also changes accordingly, but the page displays the corresponding value of the first selection. With confusion, I opened Baidu. 

Page code: (select selection values ​​are obtained from the interface) 

  •  problem causes:

By trying to find out, the printed array value has changed, but the page has not changed.
After testing, it is found that directly assigning values ​​to array elements or computing operations vue cannot monitor array changes.
Due to JavaScript limitations, Vue cannot detect the following changes to the array :
when you directly set an item by index, for example: vm.items[indexOfItem] = newValue
when you modify the length of the array, for example: vm.items.length = newLength

According to vue's official documentation: Vue contains a set of mutation methods for observing arrays, so they will trigger view updates.  These methods are as follows:

push() pop() shift() unshift() splice() sort() reverse()

So when we want the page to update in real time, we must use the above method.
For example: when we realize the function of modifying the number of shopping carts, we need to render the data in the array through v-for. 

  • problem solved:

It is not difficult to find that when we click on the addition and subtraction, we can pass

this.numberArr.splice(index, 1, sum);

 Arrays are mutated by the splice method. Pass the v-for index to the click function when binding the click event. Its function is used as follows: 

删除:
//删除起始下标为1,长度为1的一个值(len设置1,如果为0,则数组不变)
var arr = ['a','b','c','d'];
arr.splice(1,1);
console.log(arr);  
//['a','c','d']; 


//删除起始下标为1,长度为2的一个值(len设置2)
var arr2 = ['a','b','c','d']
arr2.splice(1,2);
console.log(arr2); 
//['a','d']

替换:
//替换起始下标为1,长度为1的一个值为‘ttt’,len设置的1
var arr = ['a','b','c','d'];
arr.splice(1,1,'ttt');
console.log(arr);        
//['a','ttt','c','d'] 

//替换起始下标为1,长度为2的两个值为‘ttt’,len设置的1
var arr2 = ['a','b','c','d'];
arr2.splice(1,2,'ttt');
console.log(arr2);       
//['a','ttt','d'] 

添加:
//在下标为1处添加一项'ttt'

var arr = ['a','b','c','d'];
arr.splice(1,0,'ttt');
console.log(arr);        
//['a','ttt','b','c','d'] 

Guess you like

Origin blog.csdn.net/qq_42857603/article/details/108463369