父組件如何獲取子組件數據,子組件如何獲取父組件數據,父子組件如何傳值


1、父組件如何主動獲取子組件的數據

方案1:$children

$children用來訪問子組件實例,要知道一個組件的子組件可能是不唯一的,所以它的返回值是個數組

定義Header、HelloWorld兩個組件

<template>
  <div class="index">
    <Header></Header>
    <HelloWorld :message="message"></HelloWorld>
    <button @click="goPro">跳轉</button>
  </div>
</template>
mounted(){
 console.log(this.$children)
}

打印的是個數組,可以用foreach分別得到所需要的數據

缺點:

無法確定子組件的順序,也不是響應式的

方案2: $refs

<HelloWorld ref="hello" :message="message"></HelloWorld>

調用hellworld子組件的時候直接定義一個ref,這樣就可以通過this.$refs獲取所需要的數據。

this.$refs.hello.屬性
this.$refs.hello.方法

2.子組件如何主動獲取父組件中的數據

通過$parent

parent用來訪問父組件實例,通常父組件都是唯一確定的,跟children類似

this.$parent.屬性
this.$parent.方法

父子組件通信除了以上三種,還有props和emit。此外還有inheritAttrs和attrs

3.inheritAttrs

這是2。4新增的屬性和接口。inheritAttrs屬性控制子組件html屬性上是否顯示父組件提供的屬性。

如果我們將父組件Index中的屬性desc、ketsword、message三個數據傳遞到子組件HelloWorld中的話,如下

父組件Index部分

<HelloWorld ref="hello" :desc="desc" :keysword="keysword" :message="message"></HelloWorld>

子組件:HelloWorld,props中只接受了message

props:{
  message: String  
}

實際情況,我們只需要message,那其他兩個屬性則會被當作普通的html元素插在子組件的根元素上

這樣做會使組件預期功能變得模糊不清,這個時候,在子組件中寫入,inheritAttrs:false,這些沒用到的屬性便會被去掉,true的話,就會顯示。

props:{
  message: String  
},
inheritAttrs:false

 

如果父組件沒被需要的屬性,跟子組件本來的屬性沖突的時候

<HelloWorld ref="hello" type="text" :message="message"></HelloWorld>

子組件:helloworld

<template>
  <input type="number">
</template>

這個時候父組件中type="text",而子組件中type="number",而實際中最后顯示的是type="text",這並不是我們想要的,所以只要設置inheritAttrs:false,type便會成為number。

那么上述這些沒被用到的屬性,如何被獲取。這就用到了$attrs

3.$attrs

作用:可以獲取到沒有使用的注冊屬性,如果需要,我們在這也可以往下繼續傳遞。

就上述沒有用到的desc和keysword就能通過$attrs獲取到

通過$attr的這個特性可以父組件傳遞到子組件,免除父組件傳遞到子組件,再從子組件傳遞到孫組建的麻煩

父組件Index部分

<div class="index">
  <HelloWorld ref="hello" :desc="desc" :keysword="keysword" :message="message"></HelloWorld>
</div>

子組件helloworld部分

<div class="hello">
   <sunzi v-bind="$attrs"></sunzi>
   <button @click="aa">獲取父組件的數據</button>
</div>

孫組建

<template>
  <div class="header">
    {{$attrs}}
    <br>
  </div>
</template>

可以看出通過v-bind="$attrs"將數組傳到孫組建中

除了以上,provide/inject也適用於隔代組件通信,尤其是獲取祖先組建的數據,非常方便

provide 選項應該是一個對象或返回一個對象的函數

provide:{
  for:'demo'  
}
inject:['for']

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM