---轉(zhuǎn)載keepfool的60分鐘組件快速入門(下篇)
父組件訪問子組件榜晦,子組件訪問父組件低匙,或者是子組件訪問根組件硼端。針對這幾種情況州丹,Vue.js都提供了相應(yīng)的API:
- 父組件訪問子組件:
$children
或$refs
$children
在父組件中,通過this.$children可以訪問子組件刁憋。
this.$children是一個(gè)數(shù)組滥嘴,它包含所有子組件的實(shí)例。
$refs
<template id="parent-component">
<child-component1 v-ref:cc1></child-component1>
<child-component2 v-ref:cc2></child-component2>
<button v-on:click="showChildComponentData">顯示子組件的數(shù)據(jù)</button>
</template>
在父組件中至耻,則通過$refs.索引ID訪問子組件的實(shí)例:
showChildComponentData: function() {
alert(this.$refs.cc1.msg);
alert(this.$refs.cc2.msg);
}
- 子組件訪問父組件:
$parent
下面這段代碼定義了兩個(gè)組件:child-component和它的父組件parent-component若皱。在子組件中,通過this.$parent可以訪問到父組件的實(shí)例尘颓。
<div id="app">
<div id="app">
<parent-component></parent-component>
</div>
<template id="parent-component">
<child-component></child-component>
</template>
<template id="child-component">
<h2>This is a child component</h2>
<button v-on:click="showParentComponentData">顯示父組件的數(shù)據(jù)</button>
</template>
<script src="js/vue.js"></script>
<script>
Vue.component('parent-component', {
template: '#parent-component',
components: {
'child-component': {
template: '#child-component',
methods: {
showParentComponentData: function() {
alert(this.$parent.msg)
}
}
}
},
data: function() {
return {
msg: 'parent component message'
}
}
})
new Vue({
el: '#app'
})
</script>
- 子組件訪問根組件:
$root