有時候我們需要父組件訪問子組件,子組件訪問父組件,或者是子組件訪問根組件。
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點了,晚安!