爺孫組件之間的傳值


Vue 項目中,組件之間的通信,用到最多的就是 父子組件、兄弟組件之間的傳值,但是最近遇到一個爺孫組件,甚至更深一層的組件之間的傳值,通過查資料,終於解決了。

(1)通過 $attrs 和 $listeners 來傳值 

          下面是官網介紹:

 

具體的咱也沒看明白,直接照着葫蘆畫瓢了,

首先創建一個Father 組件, 向子組件和孫組件傳值,以及接收孫組件傳來的方法

<template>
  <div class="page">
      我是爺爺輩的
      <div>孫子傳來的{{grandsonMsg}}</div>
       <children @sendGra='sendGra' :son='son' :grand='grand' :clickSend='clickSend'></children>
      
  </div>
</template>

<script>
import children from './children'
export default {
    name:'father',
    components:{
        'children':children
    },
    data(){
        return{
            grandsonMsg:'',
            son:'給兒子的',
            grand:'給孫子的'
        }
    },
    provide() {
        return {
            provideData: '爺爺組件第二種傳值' // 祖先組件提供數據
        }
    },
    methods:{
        sendGra(ele){  //孫子傳來的方法
            this.grandsonMsg = ele
        },
        clickSend(){
            console.log('爺爺傳給孫子的方法');
        }
    }
}
</script>

<style>
body{
    padding:100px;
}
.page{
    padding: 100px;
}
</style>

  然后創建子組件,通過v-bind:'$attrs'來存貯父組件傳給孫組件的值 和 v-on:'$listeners'來接送孫組件傳給爺組件的事件

 

  注意: 傳給孫組件的數值,在子組件中不可以用props 來進行聲明   需要設置  inheritAttrs: false,取消默認行為

<template>
  <div>
      <div>--------</div>
     我是兒子輩的
     <grandson v-on="$listeners" v-bind="$attrs"></grandson>
  </div>
</template>

<script>
import grandson from './grandson'
export default {
    components:{
        grandson
    },
    inheritAttrs: false,
}
</script>

<style>

</style>

  第三步,創建孫組件接收數據和傳遞事件(此組件也不能用props 來接收 )傳遞多個時用,$attrs.name 來進行接收

<template>
  <div>
      <div>--------</div>
      <button @click="send">傳值</button>
      <div>{{grand}}</div>
      <div>$attrs{{$attrs}}</div>
      <div>{{provideData}}</div>
  </div>
</template>

<script>
export default {
    props:['grand'],
    data(){
        return{
            sendMsg:'我是你的孫子',
        }
    },
    inheritAttrs: false,
    inject:['provideData'],
    methods:{
        send(){
            this.$emit('sendGra',this.sendMsg)
        }
    }
}
</script>

<style>

</style>

  (2)通過provide 和 inject 來進行傳值,提示:provide 和 inject 綁定並不是可響應的。這是刻意為之的。然而,如果你傳入了一個可監聽的對象,那么其對象的屬性還是可響應的。

          首先: 爺組件通過 provide 進行創建值

provide() {
        return {
            provideData: '爺爺組件第二種傳值' // 祖先組件提供數據
        }
    },

       最后,在孫組件中 進行 inject 接收

 

<template>
  <div>
      <div>{{provideData}}</div>
  </div>
</template>

<script>
export default {
    inheritAttrs: false,
    inject:['provideData'],
    methods:{
        send(){
            this.$emit('sendGra',this.sendMsg)
        }
    }
} 

       友情提示

   1. provide/inject是解決組件之間的通信問題的利器,不受層級結構的限制。但也不是隨便去濫用,通信代表着耦合。

   2.provide/inject主要為高階插件/組件庫提供用例。並不推薦直接用於應用程序代碼中。

 


免責聲明!

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



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