前面的话
有时候需要父组件访问子组件,子组件访问父组件,或者是子组件访问根组件。 在组件实例中,Vue提供了相应的属性,包括$parent、$children、$refs和$root,这些属性都挂载在组件的this上。本文将详细介绍Vue组件实例间的直接访问
$parent
$parent表示父组件的实例,该属性只读
下面是一个简易实例
<div id="example">
<parent-component></parent-component>
</div>
<template id="parent-component">
<div class="parent">
<h3>我是父组件</h3>
<input v-model="parentMsg">
<p>{{parentMsg}}</p>
<child-component></child-component>
</div>
</template>
<template id="child-component">
<div class="child">
<h3>我是子组件</h3>
<p>{{msg}}</p>
<button v-on:click="showData">显示父组件数据</button>
</div>
</template>
<script>
// 注册
Vue.component('parent-component', {
template: '#parent-component',
data(){
return{
parentMsg:'我是父组件的数据'
}
},
components:{
'child-component':{
template:'#child-component',
data(){
return{
msg:''
}
},
methods:{
showData(){
this.msg = this.$parent.parentMsg;
}
}
}
}
})
// 创建根实例
new Vue({
el: '#example'
})
</script>
<iframe style="width: 100%; height: 260px;" src="http://owbhsauev.bkt.clouddn.com/vue/module/m19.html" frameborder="0" width="320" height="240">
$root
$root表示当前组件树的根 Vue 实例。如果当前实例没有父实例,此实例将会是其自己。该属性只读
<div id="example">
<h3>我是根组件</h3>
<input v-model="rootMsg">
<p>{{rootMsg}}</p>
<parent-component></parent-component>
</div>
<template id="parent-component">
<div class="parent">
<h3>我是父组件</h3>
<input v-model="parentMsg">
<p>{{parentMsg}}</p>
<child-component></child-component>
</div>
</template>
<template id="child-component">
<div class="child">
<h3>我是子组件</h3>
<p>
<button v-on:click="showRootData">显示根组件数据</button><span>{{rootMsg}}</span>
</p>
<p>
<button v-on:click="showParentData">显示父组件数据</button><span>{{parentMsg}}</span>
</p>
</div>
</template>
<script>
// 注册
Vue.component('parent-component', {
template: '#parent-component',
data(){
return{
parentMsg:'我是父组件的数据'
}
},
components:{
'child-component':{
template:'#child-component',
data(){
return{
parentMsg:'',
rootMsg:''
}
},
methods:{
showParentData(){
this.parentMsg = this.$parent.parentMsg;
},
showRootData(){
this.rootMsg = this.$root.rootMsg;
},
}
}
}
})
// 创建根实例
new Vue({
el: '#example',
data:{
rootMsg:'我是根组件数据'
}
})
</script>
<iframe style="width: 100%; height: 390px;" src="http://owbhsauev.bkt.clouddn.com/vue/module/m20.html" frameborder="0" width="320" height="240">
$children
$children表示当前实例的直接子组件。需要注意$children
并不保证顺序,也不是响应式的。如果正在尝试使用$children
来进行数据绑定,考虑使用一个数组配合v-for
来生成子组件,并且使用Array作为真正的来