Vue從零開始總結(jié)29
父傳子實現(xiàn)了,那么接下來就是父訪問子了。
在父組件中使用指定函數(shù),
第一種方法:在指定函數(shù)內(nèi)使用$children獲取子組件中的內(nèi)容
代碼如下:
<template id="son">
?<div> <h2>{{message}}</h2></div>
</template>
<div id="app">
<cpn></cpn>
?<button @click="btnClick">獲取</button>
</div>
const app=new Vue({
? ?el:document.querySelector('#app'),
? ?data:{
? ?num1:0,
? ?num2:1
?}, components:{
? ? ?cpn:{
? ? ? ?template:'#son',
? ? ? ?data(){
? ? ? ? ?return {
? ? ? ? ? ?message:'子組件中的數(shù)據(jù)'
? ? ? ? ?}
? ? ? ?}
? ? ?}
?},
?methods: {
? ?btnClick(){
? ? ?console.log(this.$children);
? ?}
?}
})

我們發(fā)現(xiàn)通過$children獲取到的是數(shù)組。
當使用多個cpn,相當于創(chuàng)建了多個不同的實例,這些實例以數(shù)組的形式存儲在VueComponent里,下標從0開始,uid從1開始
<div id="app">
<cpn></cpn>
<cpn></cpn>
<cpn></cpn>
?<button @click="btnClick">獲取</button>
</div>
btnClick(){
?for (let x of this.$children)
?{
? ?console.log(x);
?}
}

第二種方法:在指定函數(shù)內(nèi),使用$refs獲取子組件中的數(shù)據(jù)
@one.當我們未在子組件標簽行內(nèi)指定ref值時

發(fā)現(xiàn)獲取到的是空對象,里面空空如也
@two.當我們在子組件標簽行內(nèi)指定ref值時
<div id="app">
<cpn ref="a"></cpn>
<cpn ref="b"></cpn>
<cpn ref="c"></cpn>
?<button @click="btnClick">獲取</button>
</div>
btnClick(){
?console.log(this.$refs);
}

發(fā)現(xiàn)獲取到了相應ref值的對象。
那么接下來就可以通過ref值來訪問子組件里的數(shù)據(jù)了
btnClick(){
?console.log(this.$refs.a.message);
}
