1、触发视图的更新
- push:在末尾添加元素
- pop:删除末尾的元素
- splice:删除元素
- reverse:翻转数组
- shift:删除第一个元素
- unshift:在开头添加元素
- sort:排序
<template>
<div class="ShuZhu">
<ul>
<li v-for="item in arr" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="add">添加</button>
<button @click="del">删除</button>
<button @click="rem">清空</button>
<button @click="rev">翻转</button>
</div>
</template>
<script>
export default {
name: "ShuZhu",
data() {
return {
arr: [
{id: 1, name: "张三"},
{id: 2, name: "李四"},
{id: 3, name: "王五"},
{id: 4, name: "赵六"},
]
}
},
created() {
},
methods: {
add() {
this.arr.push({id: this.arr.length + 1, name: "添加"})
},
del() {
this.arr.pop();
},
rem() {
this.arr.splice(0, this.arr.length)
},
rev() {
this.arr.reverse();
}
}
}
</script>
2、不可以触发视图的更新
- 利用数组的索引值设置数组的元素
- 直接修改数组的长度
<template>
<div class="ShuZhu">
<ul>
<li v-for="item in arr" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="add">添加</button>
<button @click="del">删除</button>
<button @click="rem">清空</button>
<button @click="rev">翻转</button>
</div>
</template>
<script>
export default {
name: "ShuZhu",
data() {
return {
arr: [
{id: 1, name: "张三"},
{id: 2, name: "李四"},
{id: 3, name: "王五"},
{id: 4, name: "赵六"},
]
}
},
created() {
},
methods: {
add() {
this.arr[this.arr.length] = {id: this.arr.length+1, name: "添加"}
console.log(this.arr);
},
del() {
this.arr.length -= 1;
console.log(this.arr);
},
rem() {
this.arr.length = 0;
console.log(this.arr);
},
rev() {
let t;
for (let i = 0; i < this.arr.length / 2; i++) {
t = this.arr[i];
this.arr[i] = this.arr[this.arr.length - 1 - i];
this.arr[this.arr.length - i - 1] = t;
}
console.log(this.arr);
}
}
}
</script>
解决办法:
- 通过
this.$set
,格式:this.$set(obj , key , value)
add() {
this.$set(this.arr,this.arr.length,{id: this.arr.length+1, name: "添加"});
console.log(this.arr);
}
- 通过
Object.assign
或者扩展运算符
实现
add() {
this.arr[this.arr.length] = {id: this.arr.length + 1, name: "添加"};
this.arr = [...this.arr]
console.log(this.arr);
}
或者
add() {
this.arr[this.arr.length] = {id: this.arr.length + 1, name: "添加"};
this.arr=Object.assign([],this.arr);
console.log(this.arr);
}