1.v-for遍历循环对象与数组

2.vue数组更新检测变异方法举例

<template>
<div class="jz">
<div>
<h2>遍历数组</h2>
<ul>
<li style="font-size: 16px" v-for="(fx, index) in fxs" :key="index">
{{fx.name}}:{{fx.age}}
<Button @click="deleteP(index)">delete</Button>
<Button @click="updateP(index, {name: 'newFx', age: 18})">update</Button>
</li>
</ul>
</div>
<br>
<div>
<h2>遍历对象</h2>
<ul>
<li style="font-size: 16px" v-for="(item, key) in fxs[0]" :key="key">
{{key}}:{{item}}
</li>
</ul>
</div>

</div>
</template>

<script>
export default {
data () {
return {
fxs: [
{name: 'fxOne', age: 1},
{name: 'fxTwo', age: 2},
{name: 'fxThree', age: 3},
{name: 'fxFour', age: 4},
]
}
},
methods: {
deleteP (index) {
console.log(index)
this.fxs.splice(index, 1) // 调用了不是原生数组的splice(), 而是一个变异(重写)方法
// 1. 调用原生的数组的对应方法
// 2. 更新界面
},
updateP (index, newP) {
// 由于 JavaScript 的限制,Vue 不能检测以下数组的变动(页面不会更新):
// 1.当你利用索引直接设置一个数组项时 2.当你修改数组的长度时
// this.fxs[index] = newP
this.fxs.splice(index, 1, newP)
},
}
}
</script>
<style>
.hidden {
display: none;
}

.show {
display: block;
}

.jz {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
border: 1px solid green;
text-align: center
}
</style>

数组更新检测的变异方法:Vue 将被侦听的数组的变异方法进行了包裹,所以它们也将会触发视图更新。这些被包裹过的方法包括:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

变异方法,会改变调用了这些方 法的原始数组。相比之下,也有非变异 (non-mutating method) 方法,例如 ​​filter()​​​、​​concat()​​​ 和 ​​slice()​​ 。它们不会改变原始数组,而总是返回一个新数组。当使用非变异方法时,可以用新数组替换旧数组:

vue之v-for列表循环,数组更新检测的变异方法详解_遍历数组