vue 父链和子组件索引_vuejs填坑-父子组件之间的访问
有時(shí)候我們需要父組件訪問子組件,子組件訪問父組件,或者是子組件訪問根組件。
1. 父組件訪問子組件 $children或$ref
$children 返回所有子組件的實(shí)例,是一個(gè)數(shù)組
顯示兩個(gè)組件的信息
{{ 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 有時(shí)候組件過多的話,就很記清各個(gè)組件的順序與位置,所以通過給子組件一個(gè)索引ID
顯示兩個(gè)組件的信息
{{ 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 當(dāng)前組件樹的根 Vue 實(shí)例。如果當(dāng)前實(shí)例沒有父實(shí)例,此實(shí)例將會(huì)是其自已。
父組件中的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點(diǎn)了,晚安!
總結(jié)
以上是生活随笔為你收集整理的vue 父链和子组件索引_vuejs填坑-父子组件之间的访问的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 甲醛溶水里吗
- 下一篇: html5倒计时秒杀怎么做,vue 设