The modified array of vue remodeling array specifies the value operation of index
- 2021-08-06 20:13:19
- OfStack
As shown below:
vm.items[indexOfItem] = newValue
vue cannot detect changes in arrays
Want to implement the set method that can use vue
this.$set(this.items,indexOfItem,newValue);
Supplementary knowledge: In vue, setting an array item directly by index can not trigger view update
Due to the limitation of JavaScript, Vue cannot detect changes in the following arrays:
1. When you set an array item directly using an index, for example: vm. items [indexOfItem] = newValue
2. When you modify the length of the array, for example: vm. items. length = newLength
For example:
var vm = new Vue({
data: {
items: ['a', 'b', 'c']
}
})
vm.items[1] = 'x' // Not responsive
vm.items.length = 2 // Not responsive
To solve the Class 1 problem, the following two methods can achieve the same effect as vm. items [indexOfItem] = newValue, and will also trigger status updates within a responsive system:
// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)
You can also use the vm. $set instance method, which is an alias for the global method Vue. set:
vm.$set(vm.items, indexOfItem, newValue)
To solve Class 2 problems, you can use splice:
vm.items.splice(newLength)