v-for更新监测
先看案例
<template>
<div>
<ul>
<li v-for="(item, index) in arrList" :key="index">
{{ item}}
</li>
</ul>
<button @click="revBtn">数组翻转</button>
<button @click="sliceBtn">截取前3个</button>
<button @click="updateBtn">更新第一个元素值</button>
</div>
</template>
<script>
export default {
data(){
return {
arrList: [1, 3, 5, 7, 9]
}
},
methods: {
//数组翻转
revBtn(){
// 1. 数组翻转可以让v-for更新
this.arrList.reverse()
},
//数组截取
sliceBtn(){
// 2. 数组slice方法不会造成v-for更新
// slice不会改变原始数组
// this.arrList.slice(0, 3)
// 解决v-for更新 - 覆盖原始数组
let newArr = this.arrList.slice(0, 3)
this.arrList= newArr
},
//更新值
updateBtn(){
// 3. 更新某个值的时候, v-for是监测不到的
// this.arrList[0] = 1000;
// 解决-this.$set()
// 参数1: 更新目标结构
// 参数2: 更新位置
// 参数3: 更新值
this.$set(this.arrList, 0, 1000)
}
}
}
</script>
<style>
</style>
以上是我们使用v-for渲染数据的操作,总结如下:
① 数组变更方法, 就会导致v-for更新, 页面更新
② vue不能监测到数组里赋值的动作而更新, 如果需要请使用Vue.set() 或者this.$set(), 或者覆盖整个数组
③ 改变原数组的方法才能让v-for更新
这些方法会触发数组改变, v-for会监测到并更新页面
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
这些方法不会触发v-for更新
slice()
filter()
concat()