最近在做項目的過程中遇到一個問題,我們創建自己的組件時,父組件傳給子組件一個數組,子組件使用v-for指令無法渲染,以下是錯誤代碼:
Vue.component('component-test',{
props: {
testData: {
type: Array,
default: []
}
},
template: '<li v-for="(item,index) in testData">{{item}}</li>'
})
當我們使用watch監聽testData變化時發現testData的值已經改變,但頁面上卻沒有響應渲染出對應的元素。
但如果給模板(template)套上一個父元素,再使用v-for時,發現又可以成功渲染了,成功代碼如下:
Vue.component('component-test',{
props: {
testData: {
type: Array,
default: []
}
},
template: `<ul>
<li v-for="(item,index) in testData">{{item}}</li>
</ul>`
})
以上的區別也就是在v-for元素上加一個父元素套起來而已,然而其中的原理至今尚未明白,百思不得解。哪位大神知道原因的勞煩告知,感謝!!!