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

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

方案1:$children數組

$children用來訪問子組件實例,要知道一個組件的子組件多是不惟一的,因此它的返回值是個數組ide

定義Header、HelloWorld兩個組件函數

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

打印的是個數組,能夠用foreach分別獲得所須要的數據this

缺點:spa

沒法肯定子組件的順序,也不是響應式的code

方案2: $refshtm

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

調用hellworld子組件的時候直接定義一個ref,這樣就能夠經過this.$refs獲取所須要的數據。對象

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

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

經過$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']
相關文章
相關標籤/搜索