学习优先度:★★★★☆

难易度:★★★☆☆

Vue 的反应性系统不会检测数组索引的更改或数组长度的修改。

在 Vue 中处理数组时,直接修改数组索引或更改数组长度不会触发反应性。相反,您应该使用 Vue 的数组突变方法来确保跟踪更改。

【代码示例】

// Creating a reactive array in Vue
const vm = new Vue({
 data: {
  items: [1, 2, 3]
 }
});
// Directly setting an array index
vm.items[3] = 4;
// Vue will not react to this change
console.log(vm.items); // Output: [1, 2, 3, 4] (but Vue reactivity doesn't track this change)
// Correct way to modify an array reactively
vm.items.push(4);
// Vue will now react to this change
console.log(vm.items); // Output: [1, 2, 3, 4] (Vue reactivity tracks this change)

【执行结果】

// Output: [1, 2, 3, 4] (but Vue reactivity doesn't track this change)
// Output: [1, 2, 3, 4] (Vue reactivity tracks this change)

Vue 的反应性系统使用 push、pop、shift、unshift、splice、sort 和 reverse 等数组突变方法来确保跟踪数组的变化。直接设置数组元素或修改其长度会绕过 Vue 的反应性系统,从而导致用户界面无法按预期更新。

【补充】

Vue 提供了一组数组突变方法,旨在与其反应性系统无缝协作。使用这些方法可确保组件的状态与用户界面保持同步,从而防止出现错误并确保一致的用户体验。