先看下面一個例子:
<template>
<div>
<button @click="clickHandler">刪除</button>
<template>
<div v-for="(item, index) in list" :key="index" >{{item.name}}</div>
</template>
</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
list: [
{
id: 1,
name: 'Person1'
},
{
id: 2,
name: 'Person2'
},
{
id: 3,
name: 'Person3'
},
{
id: 4,
name: 'Person4'
}
]
}
},
methods: {
clickHandler () {
// 刪除第二個數(shù)據(jù)
this.list.splice(1, 1)
}
}
}
</script>
<style scoped>
</style>
當點擊按鈕時,會刪除數(shù)組第二個數(shù)據(jù),這樣就會導致原數(shù)組第二個數(shù)據(jù)之后數(shù)據(jù)的index發(fā)生改變,從而導致person3,和person4節(jié)點的更新,增加了額外的性能開銷;
如果將key由綁定index改為綁定id,上述性能開銷的問題就不會存在,因為更換key綁定時,刪除第二個數(shù)據(jù),person3和person4的id并未發(fā)生改變,dom也不會發(fā)生更新;
結論:文章來源:http://www.zghlxwxcb.cn/news/detail-787993.html
- 對于沒有交互的簡單數(shù)組使用for時,而且數(shù)組沒有唯一的id時,可考慮使用index作為key;
- 其它情況,盡可能使用唯一的id作為for循環(huán)的key值
參考鏈接文章來源地址http://www.zghlxwxcb.cn/news/detail-787993.html
到了這里,關于vue for循環(huán)不建議使用index作為key的原因的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!