0
我使用$refs
來綁定子組件,但無法從父組件通過$ref.refname.msg
獲取子組件的值。 (我試過$children
可以工作)。
msg的子組件已被定義。
信息可以通過
parent.$chidren.msg
得到。
但錯誤表明:
Uncaught TypeError: Cannot read property 'msg' of undefined.
這裏的HTML代碼。
<template id="parent-component" ref='parent'>
<div>
<child-component1></child-component1>
<child-component2></child-component2>
<button v-on:click="showChildData">Show child component data</button>
</div>
</template>
<template id="child-component1" ref="cc1">
<div>
<span> This is child component 1.</span>
<button v-on:click="showParentData">Show parent component data</button>
</div>
</template>
<template id="child-component2" ref="cc2">
<div>
<span> This is child component 2.</span>
<button v-on:click="showParentData">Show parent component data</button>
</div>
</template>
<div id="e15">
<parent-component></parent-component>
</div>
這裏的JavaScript:
Vue.component('parent-component',{
template: '#parent-component',
components: {
'child-component1': {
template: '#child-component1',
data: function(){
return {
msg: 'This is data of cc1'
};
},
methods: {
showParentData: function(){
alert(this.$parent.msg);
}
}
},
'child-component2': {
template: '#child-component2',
data: function() {
return {
msg: 'This is data of cc2',
num: 12
};
},
methods: {
showParentData: function(){
alert(this.$parent.msg);
}
}
}
},
data: function() {
return {
msg: 'This is data of parent.'
};
},
methods: {
showChildData: function(){
for(var i=0;i<this.$children.length;i++){
alert(this.$children[i].msg);
// console.log(this.$children[i]);
}
//!!!!This line doesn't work!!!
alert(this.$refs.cc2.msg);
}
}
});
var e15 = new Vue({
el: '#e15'
});
問題解決了。非常感謝!! –
@YaoIris如果解決了問題,請將此答案標記爲「已接受」 –