列表循环渲染
一、v-for循环数组
- 为了提高循环时性能,在数组其中一项变化后,整个数组不进行全部重新渲染,Vue提供了绑定key值的使用方法,目的就是增加渲染性能,避免重复渲染
- 增加数据内容的三种方式:
① 使用数组变更函数pop,push,shift,unshift,reverse等
<script type="text/javascript">
const app = Vue.createApp({
data() {
return {
listArray:['123','456','789'],
}
},
methods: {
handleAddClick(){
this.listArray.unshift("hello");
this.listArray.push("hello");
this.listArray.pop();
this.listArray.shift();
this.listArray.reverse("hello");
}
},
template:`
<button @click="handleAddClick">新增</button>
<div v-for="(value,index) in listArray" :key="index">
{{index}}--{{value}}
</div>
`
});
const vm = app.mount('#root')
</script>
② 直接替换数组
<script type="text/javascript">
const app = Vue.createApp({
data() {
return {
listArray:['123','456','789'],
}
},
methods: {
handleAddClick(){
this.listArray = ["bye","world"];
this.listArray = ['bye'].concat(['world']);
this.listArray = ['bye','world'].filter(item=>item ==='bye');
}
},
template:`
<button @click="handleAddClick">新增</button>
<div v-for="(value,index) in listArray" :key="index">
{{index}}--{{value}}
</div>
`
});
const vm = app.mount('#root')
</script>
③ 直接更新数组内容
<script type="text/javascript">
const app = Vue.createApp({
data() {
return {
listArray:['123','456','789'],
}
},
methods: {
handleAddClick(){
this.listArray[0] ='hello'
}
},
template:`
<button @click="handleAddClick">新增</button>
<div v-for="(value,index) in listArray" :key="index">
{{index}}--{{value}}
</div>
`
});
const vm = app.mount('#root')
</script>
二、v-for循环对象
问题:一个标签中同时使用v-for和v-if时,循环的优先级高于if的优先级,v-if不生效
方法:在v-for标签内嵌套增加一个新标签(可用标签,对结构无影响)使用v-if
<script type="text/javascript">
const app = Vue.createApp({
data() {
return {
listObject:{
Name:"A",
Age:18
}
}
},
methods: {
handleAddClick(){
// 直接添加对象的内容
this.listObject.height = "188cm";
this.listObject.Sex="male";
}
},
template:`
<button @click="handleAddClick">新增</button>
<template
v-for="(value,key,index) in listObject" :key="index">
<div v-if = "key!=='Age'">
{{index}}--{{key}}--{{value}}
</div>
</template>
<div v-for="item in 10">{{item}}</div>
`
});
const vm = app.mount('#root')
</script>