下午寫 Vue $parent 實例時,總是遇到這個問題,不禁讓人陷入沉思

1.gif
Vue,醒醒啊,你怎么了,貼上子組件源代碼
<template>
<div>
<child-component1></child-component1>
<child-component2></child-component2>
<button v-on:click="showChildComponentData">顯示子組件的數(shù)據(jù)</button>
</div>
</template>
<script>
export default{
components: {
'child-component1': {
template: '#child-component1',
data: function () {
return {
msg: 'child component 111111'
}
}
},
'child-component2': {
template: '#child-component2',
data: function () {
return {
msg: 'child component 222222'
}
}
}
},
methods: {
showChildComponentData: function () {
for (var i = 0; i < this.$children.length; i++) {
alert(this.$children[i].msg)
}
}
}
}
</script>
這是報錯信息:

1.png
修改后的代碼:
<template>
<div>
<child-component1></child-component1>
<child-component2></child-component2>
<button v-on:click="showChildComponentData">顯示子組件的數(shù)據(jù)</button>
</div>
</template>
<script>
export default{
components: {
'child-component1': {
template: '<p>I am ok</p>',
data: function () {
return {
msg: 'child component 111111'
}
}
},
'child-component2': {
template: '<p>ok</p>',
data: function () {
return {
msg: 'child component 222222'
}
}
}
},
methods: {
showChildComponentData: function () {
for (var i = 0; i < this.$children.length; i++) {
alert(this.$children[i].msg)
}
}
}
}
</script>
這樣就好了,原因是 Vue 的構(gòu)建,運行時構(gòu)建刪除了模板編譯的功能,因此無法支持帶 template 屬性的 Vue 實例選項。
總結(jié):每個子組件的 template 屬性值不一樣。