列表渲染
1. v-for指令
- 用于展示列表数据
- 语法: v-for="(item, index) in xxx" :key="yyy"
- 可遍历: 数组、对象、字符串(用的很少)、指定次数(用的很少)
html
<div id="editor">
<ul>
<!--遍历数组-->
<li v-for="p in personList" :key="p.id">
{{p.name}} -- {{p.age}}
</li>
</ul>
<ul>
<!--遍历对象-->
<li v-for="(p, k) in carInfo" :key="k">
{{k}} -- {{p}}
</li>
</ul>
<ul>
<!--遍历字符串-->
<li v-for="(s, k) in msg" :key="k">
{{k}} --- {{s}}
</li>
</ul>
<ul>
<!--遍历指定次数-->
<li v-for="(num, k) in 6" :key="k">
{{k}} -- {{num}}
</li>
</ul>
</div>
js
<script>
Vue.config.productionTip=false
new Vue({
el: "#editor",
data() {
return {
personList: [
{id: '0001', name: '刘德华', age: 23},
{id: '0002', name: '章子怡', age: 37},
{id: '0003', name: '毛晓彤', age: 13},
{id: '0004', name: '张碧晨', age: 20}
],
carInfo: {brand: '奥迪Q8', weight: '1.8吨', long: '5米', power:"四驱"},
msg: "大家来一起学习Vue"
}
}
});
</script>
html
<div id="editor">
<input v-model:value="inputStr">
<ul>
<li v-for="p in filterPerson" :key="p.id">
{{ p.name }} -- {{ p.age }}
</li>
</ul>
</div>
js
<script>
Vue.config.productionTip = false
const vm = new Vue({
el: "#editor",
data() {
return {
inputStr: '',
personList: [
{id: '0001', name: '刘德华', age: 23},
{id: '0002', name: '章子怡', age: 37},
{id: '0003', name: '毛晓彤', age: 13},
{id: '0004', name: '张碧晨', age: 20}
]
}
},
computed: {
filterPerson() {
return this.personList.filter((p) => {
return p.name.indexOf(this.inputStr)!==-1
})
}
}
})
</script>
html
<div id="editor">
<input v-model:value="inputStr">
<button @click="sortType=1">列表升序</button>
<button @click="sortType=2">列表降序</button>
<button @click="sortType=3">原顺序</button>
<ul>
<li v-for="p in filterPerson" :key="p.id">
{{ p.name }} -- {{ p.age }}
</li>
</ul>
</div>
js
<script>
Vue.config.productionTip = false
const vm = new Vue({
el: "#editor",
data() {
return {
inputStr: '',
sortType: 3,
personList: [
{id: '0001', name: '刘德华', age: 23},
{id: '00011', name: '刘德华2', age: 21},
{id: '0002', name: '章子怡', age: 37},
{id: '00022', name: '章子怡2', age: 44},
{id: '0003', name: '毛晓彤', age: 13},
{id: '00033', name: '毛晓彤2', age: 18},
{id: '0004', name: '张碧晨', age: 20},
{id: '00044', name: '张碧晨2', age: 17}
]
}
},
computed: {
filterPerson() {
// 使用indexOf判断输入字符串是否存在,特殊的空白字符串''在第一个位置,也就是0,不存在是-1
let filterPerson = this.personList.filter((p) => {
return p.name.indexOf(this.inputStr) !== -1
})
// 判断是否排序
if (this.sortType !== 3) {
// 使用sort排序, p1-p2为升序,p2-p1为降序
filterPerson.sort((p1, p2) => {
return this.sortType == 1 ? p1.age - p2.age : p2.age - p1.age
})
}
return filterPerson
}
}
})
</script>

评论