日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue 父链和子组件索引_vuejs填坑-父子组件之间的访问

發(fā)布時(shí)間:2025/3/8 vue 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue 父链和子组件索引_vuejs填坑-父子组件之间的访问 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

有時(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。