2022-12-23【技術(shù)】Vue2的12種組件通信(下)

書接上文~~

7、children /parent

children:獲取到一個包含所有子組件(不包含孫子組件)的 VueComponent 對象數(shù)組,可以直接拿到子組件中所有數(shù)據(jù)和方法等parent:獲取到一個父節(jié)點的 VueComponent 對象,同樣包含父節(jié)點中所有數(shù)據(jù)和方法等

// Parent.vue
        export default{
            mounted(){
                this.$children[0].someMethod() // 調(diào)用第一個子組件的方法
                this.$children[0].name // 獲取第一個子組件中的屬性
            }
        }
        
        // Child.vue
        export default{
            mounted(){
                this.$parent.someMethod() // 調(diào)用父組件的方法
                this.$parent.name // 獲取父組件中的屬性
            }
        }

8、provide / inject

provide / inject 為依賴注入,說是不推薦直接用于應(yīng)用程序代碼中,但是在一些插件或組件庫里卻是被常用,所以我覺得用也沒啥,還挺好用的:
provide:可以讓我們指定想要提供給后代組件的數(shù)據(jù)或方法。
inject:在任何后代組件中接收想要添加在這個組件上的數(shù)據(jù)或方法,不管組件嵌套多深都可以直接拿來用。
要注意的是 provide 和 inject 傳遞的數(shù)據(jù)不是響應(yīng)式的,也就是說用 inject 接收來數(shù)據(jù)后,provide 里的數(shù)據(jù)改變了,后代組件中的數(shù)據(jù)不會改變,除非傳入的就是一個可監(jiān)聽的對象。
所以建議還是傳遞一些常量或者方法。

// 父組件
    export default{
        // 方法一 不能獲取 methods 中的方法
        provide:{
            name:"沐華",
            age: this.data中的屬性
        },
        // 方法二 不能獲取 data 中的屬性
        provide(){
            return {
                name:"沐華",
                someMethod:this.someMethod // methods 中的方法
            }
        },
        methods:{
            someMethod(){
                console.log("這是注入的方法")
            }
        }
    }
    
    // 后代組件
    export default{
        inject:["name","someMethod"],
        mounted(){
            console.log(this.name)
            this.someMethod()
        }
    }

9、EventBus

EventBus 是中央事件總線,不管是父子組件,兄弟組件,跨層級組件等都可以使用它完成通信操作。
定義方式有三種:

// 方法一
        // 抽離成一個單獨的 js 文件 Bus.js ,然后在需要的地方引入
        // Bus.js
        import Vue from "vue"
        export default new Vue()
        
        // 方法二 直接掛載到全局
        // main.js
        import Vue from "vue"
        Vue.prototype.$bus = new Vue()
        
        // 方法三 注入到 Vue 根對象上
        // main.js
        import Vue from "vue"
        new Vue({
            el:"#app",
            data:{
                Bus: new Vue()
            }
        })

使用如下,以方法一按需引入為例:

// 在需要向外部發(fā)送自定義事件的組件內(nèi)
        <template>
            <button @click="handlerClick">按鈕</button>
        </template>
        import Bus from "./Bus.js"
        export default{
            methods:{
                handlerClick(){
                    // 自定義事件名 sendMsg
                    Bus.$emit("sendMsg", "這是要向外部發(fā)送的數(shù)據(jù)")
                }
            }
        }
        
        // 在需要接收外部事件的組件內(nèi)
        import Bus from "./Bus.js"
        export default{
            mounted(){
                // 監(jiān)聽事件的觸發(fā)
                Bus.$on("sendMsg", data => {
                    console.log("這是接收到的數(shù)據(jù):", data)
                })
            },
            beforeDestroy(){
                // 取消監(jiān)聽
                Bus.$off("sendMsg")
            }
        }

** 注意:**
1、最好再beforeDestory鉤子中,用$off解綁當(dāng)前組件用到的事件。
2、主要原理:VueComponent.prototype.proto === Vue.prototype。


主要原理

10、Vuex
Vuex 是狀態(tài)管理器,集中式存儲管理所有組件的狀態(tài)。這一塊內(nèi)容過長,如果基礎(chǔ)不熟的話可以看這個Vuex,然后大致用法如下。
比如創(chuàng)建這樣的文件結(jié)構(gòu):


image.png

index.js 里內(nèi)容如下

import Vue from 'vue'
        import Vuex from 'vuex'
        import getters from './getters'
        import actions from './actions'
        import mutations from './mutations'
        import state from './state'
        import user from './modules/user'
        
        Vue.use(Vuex)
        
        const store = new Vuex.Store({
          modules: {
            user
          },
          getters,
          actions,
          mutations,
          state
        })
        export default store

然后在 main.js 引入

import Vue from "vue"
            import store from "./store"
            new Vue({
                el:"#app",
                store,
                render: h => h(App)
            })

然后在需要的使用組件里

import { mapGetters, mapMutations } from "vuex"
                export default{
                    computed:{
                        // 方式一 然后通過 this.屬性名就可以用了
                        ...mapGetters(["引入getters.js里屬性1","屬性2"])
                        // 方式二
                        ...mapGetters("user", ["user模塊里的屬性1","屬性2"])
                    },
                    methods:{
                        // 方式一 然后通過 this.屬性名就可以用了
                        ...mapMutations(["引入mutations.js里的方法1","方法2"])
                        // 方式二
                        ...mapMutations("user",["引入user模塊里的方法1","方法2"])
                    }
                }
                
                // 或者也可以這樣獲取
                this.$store.state.xxx
                this.$store.state.user.xxx

11、$root

root 可以拿到 App.vue 里的數(shù)據(jù)和方法 通過root,任何組件都可以獲取當(dāng)前組件樹的根 Vue 實例,通過維護(hù)根實例上的 data,就可以實現(xiàn)組件間的數(shù)據(jù)共享。
通過這種方式,雖然可以實現(xiàn)通信,但在應(yīng)用的任何部分,任何時間發(fā)生的任何數(shù)據(jù)變化,都不會留下變更的記錄,這對于稍復(fù)雜的應(yīng)用來說,調(diào)試是致命的,不建議在實際應(yīng)用中使用。

//main.js 根實例
        new Vue({
            el: '#app',
            store,
            router,
            // 根實例的 data 屬性,維護(hù)通用的數(shù)據(jù)
            data: function () {
                return {
                    author: ''
                }
            },
            components: { App },
            template: '<App/>',
        });
        
        
        <!--組件A-->
        <script>
        export default {
            created() {
                this.$root.author = '于是乎'
            }
        }
        </script>
        
        
        <!--組件B-->
        <template>
            <div><span>本文作者</span>{{ $root.author }}</div>
        </template>

12、slot

就是把子組件的數(shù)據(jù)通過插槽的方式傳給父組件使用,然后再插回來。

// Child.vue
        <template>
            <div>
                <slot :user="user"></slot>
            </div>
        </template>
        export default{
            data(){
                return {
                    user:{ name:"小趙" }
                }
            }
        }
        
        // Parent.vue
        <template>
            <div>
                <child v-slot="slotProps">
                    {{ slotProps.user.name }}
                </child>
            </div>
        </template>

拓展:消息的發(fā)布和訂閱

借用第三方庫,推薦使用 pubsub-js,可以實現(xiàn)任意組件間的通信
使用方法:
1、組件A中訂閱消息(接收數(shù)據(jù))

<script>
     import pubsub from 'pubsub-js'
    export default {
      data () {
        return {
        pid:""
        }
      },
      mounted: {
          this.kpid = pubsub.subscribe('hello',function(a,b){}) 
          /*這里的回調(diào)函數(shù)使用箭頭函數(shù)可以讓回調(diào)函數(shù)中this是當(dāng)前組件的實例;
          或者用pid = pubsub.subscribe('hello',this.methodsName),其中
          methodsName是methods配置項的方法;;a接收的是消息的名字(hello),
          b接收的是真正傳過來的數(shù)據(jù)(666)
          */
      },
     beforeDestory(){
         pubsub.unsubcribe(this.pid)   
           }
    }
</script>

2、組件B中發(fā)布消息(提供數(shù)據(jù))

<script>
      import pubsub from 'pubsub-js'
    export default {
      data () {
        return {
        }
      },
      methods: {
        tellApp () {
           pubsub.publish('hello',666) 
        }
      }
    }
</script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容