有时候我们需要父组件访问子组件,子组件访问父组件,或者是子组件访问根组件。
1. 父组件访问子组件 $children或$ref
$children 返回所有子组件的实例,是一个数组
显示两个组件的信息
{{ msg }}
{{ msg }}
Vue.component('child1', {
template: '#child1',
data () {
return {
msg: '这是子组件1的信息'
}
}
})
Vue.component('child2', {
template: '#child2',
data () {
return {
msg: '这是子组件2的信息'
}
}
})
new Vue({
el: '#count',
data: {
},
methods: {
showmsg () {
for(var i = 0; i < this.$children.length; i++) {
alert(this.$children[i].msg)
}
}
}
})
$ref 有时候组件过多的话,就很记清各个组件的顺序与位置,所以通过给子组件一个索引ID
显示两个组件的信息
{{ msg }}
{{ msg }}
Vue.component('child1', {
template: '#child1',
data () {
return {
msg: '这是子组件1的信息'
}
}
})
Vue.component('child2', {
template: '#child2',
data () {
return {
msg: '这是子组件2的信息'
}
}
})
new Vue({
el: '#count',
data: {
},
methods: {
showmsg () {
alert(this.$refs.c1.msg)
alert(this.$refs.c2.msg)
}
}
})
2. 子组件访问父组件 $parent
父组件中的msg: {{ msg }}
{{ msg }}
显示父组件msg
{{ msg }}
Vue.component('child1', {
template: '#child1',
data () {
return {
msg: '这是子组件1的信息'
}
},
methods: {
showpmsg () {
alert(this.$parent.msg)
}
}
})
Vue.component('child2', {
template: '#child2',
data () {
return {
msg: '这是子组件2的信息'
}
}
})
new Vue({
el: '#count',
data: {
msg: 'hello parent'
}
})
3. 子组件访问根组件 $root 当前组件树的根 Vue 实例。如果当前实例没有父实例,此实例将会是其自已。
父组件中的msg: {{ msg }}
{{ msg }}
{{ msg }}
showrootmsg
Vue.component('child1', {
template: '#child1',
data () {
return {
msg: '这是子组件1的信息'
}
},
methods: {
showpmsg () {
alert(this.$parent.msg)
}
}
})
Vue.component('child2', {
template: '#child2',
data () {
return {
msg: '这是子组件2的信息'
}
}
})
Vue.component('cchild', {
template: '#cchild',
data () {
return {
msg: '这是子组件1的信息'
}
},
methods: {
showroot () {
alert(this.$root.msg)
}
}
})
new Vue({
el: '#count',
data: {
msg: 'hello root'
}
})
Done! 1点了,晚安!