Vue列表渲染 key 过滤 排序
列表渲染
可以遍历数组,对象,字符串以及指定次数
demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="../lib/vue.js"></script>
<body>
<div id="root">
<ul>
<h1>遍历数组</h1>
<li v-for="(p,index) in persons" :key="p.id">
<span>{{p.name}}-{{p.id}}</span>
</li>
<h1>遍历对象</h1>
<li v-for="(value,key) of personObj" :key="key" >
<span>{{value.name}} - {{value.id}}</span>
</li>
<h1>遍历字符串</h1>
<li v-for="(value,index) in personStr" >
<span>{{value}} - {{index}}</span>
</li>
<h1>遍历指定次数</h1>
<li v-for="index of 5" >
<span>{{index}}</span>
</li>
</ul>
</div>
<script>
const vm = new Vue({
el: "#root",
data: {
persons: [
{ name: 'island1', id: 1 },
{ name: 'island2', id: 2 },
{ name: 'island3', id: 3 }
],
personObj:{
island1: { name: 'island1', id: 1 },
island2: { name: 'island2', id: 2 },
island3: { name: 'island3', id: 3 }
},
personStr:'island1'
}
})
</script>
</body>
</html>
key的作用 key与index
key的作用主要是diff的时候去判断是否复用节点还是创建新的节点。
拿react说,如果key一样,并且type一样,那么表示这个节点可以复用。如果不能复用,那么就涉及到新内存的申请和旧对象内存的回收,性能上表现不一样
(content 文案不一样? 文案是作为子节点的,我们讨论的是复用当前节点)
index作为key只适用于数组的尾部操作,即数据的操作是保证先后顺序的
假如在数组头插入一个数据,以index作为key的话,那么key和type都是相同的,可以复用,就会造成第一条新数据的dom复用原来的第一个节点,导致界面出错
列表渲染、过滤、排序
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="../lib/vue.js"></script>
<body>
<div id="root">
<!-- 列表渲染 -->
<ul style="display: none;">
<button @click="add()">头插数组</button>
<li v-for="(p,index) in persons" :key="index">
<span>{{index}}</span>
<input type="text">
</li>
</ul>
<!-- 列表过滤 -->
<ul>
<input type="text" v-model="keyword" />
<button @click="sort({tag:sortTagMap.ascend})">id升序</button>
<button @click="sort({tag:sortTagMap.descend})">id降序</button>
<button @click="sort({tag:sortTagMap.origin})">原顺序</button>
<li v-for="(p,index) in filterPersons" :key="p.id">
<span>{{p.name}}</span>
</li>
</ul>
</div>
<script>
const vm = new Vue({
el: "#root",
data: {
sortTagMap: {
ascend: 'ascend',
descend: 'descend',
origin: 'origin'
},
tag: 'origin',
keyword: "",
persons: [
{ name: '1-island', id: 1 },
{ name: '2-island', id: 2 },
{ name: '3-island', id: 3 }
]
// filterPersons:[]
},
methods: {
add: function () {
this.persons.unshift({ id: 4 })
},
sort({ tag }) {
console.log(tag);
this.tag = tag
}
},
// watch: {
// keyword: {
// immediate: true,
// handler() {
// this.filterPersons = this.persons.filter(v => v.name.includes(this.keyword))
// }
// }
// },
computed: {
filterPersons() {
const { sortTagMap: map, tag } = this
const sorter = tag === map.origin ? () => { } : (tag === map.ascend ? (a, b) => a.id - b.id : (a, b) => b.id - a.id)
return this.persons.filter(v => v.name.includes(this.keyword)).sort(sorter)
}
}
})
</script>
</body>
</html>