鍍金池/ 問(wèn)答/HTML/ v-for on a <template>的一個(gè)小疑問(wèn)

v-for on a <template>的一個(gè)小疑問(wèn)

看官方文檔說(shuō)在使用v-for的時(shí)候,需要使用一個(gè)獨(dú)一無(wú)二的key值來(lái)提升性能,說(shuō)這是和虛擬dom有關(guān)。
但是我在template標(biāo)簽上面綁定v-for進(jìn)行循環(huán)的時(shí)候,綁定key值顯示報(bào)錯(cuò)了,但是頁(yè)面正常輸出數(shù)據(jù)來(lái)了

  • <template> cannot be keyed. Place the key on real elements instead.

這個(gè)意思我大概知道,應(yīng)該是說(shuō)key應(yīng)該在真是的元素上面。
難道這種情況下的v-for就不用綁定key值嗎?
代碼:
<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>vuetest.html</title>
<link rel="stylesheet" href="./main.css">
<script src="./vue.js"></script>

</head>
<body>

<div id="app">
    <template v-for='(item,index) in list' :key='item.id'>
        <p>{{item.content}}</p>
        <span>{{item.id}}</span>
    </template>
</div>
<script>
    var vm = new Vue({
        el:'#app',
        data:{
            list:[
                {
                    id:0,
                    content:'小燕子是想氣死我魏姐'
                },
                {
                    id:1,
                    content:'張雪迎工作室 澄清'
                },
                {
                    id:2,
                    content:'結(jié)婚登記率連續(xù)4年下降'
                },{
                    id:3,
                    content:'秦俊杰'
                }
            ],
        }
    })
</script>

</body>
</html>

clipboard.png

回答
編輯回答
紓惘

用key不能提升性能,是為了防止Vue默認(rèn)的元素復(fù)用導(dǎo)致某些情況下出現(xiàn)數(shù)據(jù)綁定渲染問(wèn)題,而template是虛擬節(jié)點(diǎn),不存在復(fù)用,如果你想要綁定的話,給下面的p和span標(biāo)簽綁定就好,一般只需要給和數(shù)據(jù)綁定有關(guān)的元素綁定key值

2018年9月16日 17:11