1.Vue遍历中key的作用
***作用:更新时决定节点能否被复用
***目的:精确高效的更新Vdom
***推荐使用id作为key与数组中的元素绑定,不推荐使用index;如果key对应的数据发生了变化,直接更新对应的dom就行,不用全部更新一遍。
2.vue官方:生命周期钩子那一块不是很懂。
3.Vue遍历中是否一定要增加key属性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>就地复用</title>
</head>
<body>
<div id="app">
<h3>采用就地复用策略(vuejs默认情况)</h3>
<div v-for='(p, i) in persons'>
<span>{{p.name}}<span>
<input type="text"/>
<button @click='down(i)' v-if='i != persons.length - 1'>下移</button>
</div>
<h3>不采用就地复用策略(设置key)</h3>
<div v-for='(p, i) in persons' :key='p.id'>
<span>{{p.name}}<span>
<input type="text"/>
<button @click='down(i)' v-if='i != persons.length - 1'>下移</button>
</div>
</div>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
persons: [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'C' }
]
},
mounted: function(){
// 此DOM操作将两个A的颜色设置为红色 主要是为了演示原地复用
document.querySelectorAll("h3 + div > span:first-child").forEach( v => v.style.color="red");
},
methods: {
down: function(i) {
if (i == this.persons.length - 1) return;
var listClone = this.persons.slice();
var one = listClone[i];
listClone[i] = listClone[i + 1];
listClone[i + 1] = one;
this.persons = listClone;
}
}
});
</script>
</body>
</html>