在Vue2 中使用 push等数组操作

6 min read

在Vue2中使用push等数组操作可以通过以下步骤实现:

  1. 在Vue组件中定义一个数组,例如:
data() {
  return {
    items: []
  }
}
  1. 在Vue模板中使用v-for指令循环遍历该数组,例如:
<ul>
  <li v-for="item in items">{{ item }}</li>
</ul>
  1. 在Vue组件方法中使用push等数组操作对数组进行操作,例如:
methods: {
  addItem(item) {
    this.items.push(item);
  },
  removeItem(index) {
    this.items.splice(index, 1);
  },
  clearItems() {
    this.items = [];
  }
}
  1. 在Vue模板中通过调用组件方法进行数组操作,例如:
<button @click="addItem('new item')">Add Item</button>
<button @click="removeItem(index)">Remove Item</button>
<button @click="clearItems()">Clear Items</button>

在Vue2中,当数组被修改时,Vue会自动检测并更新模板中引用该数组的部分。然而,如果直接修改数组中的某个值,则Vue无法检测到数组的修改,需要使用Vue.set方法进行修改,例如:

this.$set(this.items, index, newValue);