background
Vue cannot detect array changes due to Js limitations.
The principle of Vue bidirectional binding is to override get/set using Object.defineProperty to update the attempted attribute when the value of the attribute changes. The drawback is that if a variable method is called instead of a directly modified property, Vue does not know that its value has changed and needs to call vue.set manually to notify Vue. To mitigate this problem, Vue wraps around Array’s seven methods
var arr = [1.2.3]
arr[2] = 6
arr.length = 7
// [1, 2, 6, empty × 4]
Copy the code
Both operations in VUE will not update the view
- Modifying the array directly through the index will not update the view
- Changing the length of the array directly will not update the view
The solution
How does Vue know that when you change the value of an object, you can immediately change the results displayed on the page (so-called bidirectional binding)? It uses Object.defineProperty.
But object.defineProperty has a bug that only recognizes direct assignment of a property, obj. Property = newVal, in which case Vue knows that the value has changed and it’s time to refresh the view.
But for a mutated method, object.defineProperty is invalid and there is no way to tell if the value changed in the mutated method. In theory, in this case, a call to vue.set should appear in the code to inform Vue that a value has changed and that it is time to refresh the view.
Vue alleviates this problem by wrapping the Array variation methods so that Vue knows that the Array value has changed and it’s time to refresh the view, without requiring Vue. Set.
Vue provides seven variation methods for arrays
conclusion
- Vue contains a set of mutating methods that observe arrays, so they will also trigger view updates
- You can also use vue.$set to modify the array update view
- Do not change the length of the array directly, do not change the array by index, you will not be able to update the view