Vue3的7種和Vue2的12種組件通信,值得收藏

本文原文首發(fā)掘金:https://juejin.cn/post/6999687348120190983

如有不對的或者遺漏的,歡迎指正,你的一贊一評都是我前行最大的動力,感謝

Vue2.x組件通信12種方式寫在后面了,先來 Vue3 的

奧力給!

Vue3 組件通信方式

  • props
  • $emit
  • expose / ref
  • $attrs
  • v-model
  • provide / inject
  • Vuex

Vue3 通信使用寫法

props

用 props 傳數(shù)據(jù)給子組件有兩種方法,如下

方法一,混合寫法

// Parent.vue 傳送
<child :msg1="msg1" :msg2="msg2"></child>
<script>
import child from "./child.vue"
import { ref, reactive } from "vue"
export default {
    data(){
        return {
            msg1:"這是傳級子組件的信息1"
        }
    },
    setup(){
        // 創(chuàng)建一個響應式數(shù)據(jù)
        
        // 寫法一 適用于基礎類型  ref 還有其他用處,下面章節(jié)有介紹
        const msg2 = ref("這是傳級子組件的信息2")
        
        // 寫法二 適用于復雜類型,如數(shù)組、對象
        const msg2 = reactive(["這是傳級子組件的信息2"])
        
        return {
            msg2
        }
    }
}
</script>

// Child.vue 接收
<script>
export default {
  props: ["msg1", "msg2"],// 如果這行不寫,下面就接收不到
  setup(props) {
    console.log(props) // { msg1:"這是傳給子組件的信息1", msg2:"這是傳給子組件的信息2" }
  },
}
</script>

方法二,純 Vue3 寫法

// Parent.vue 傳送
<child :msg2="msg2"></child>
<script setup>
    import child from "./child.vue"
    import { ref, reactive } from "vue"
    const msg2 = ref("這是傳給子組件的信息2")
    // 或者復雜類型
    const msg2 = reactive(["這是傳級子組件的信息2"])
</script>

// Child.vue 接收
<script setup>
    // 不需要引入 直接使用
    // import { defineProps } from "vue"
    const props = defineProps({
        // 寫法一
        msg2: String
        // 寫法二
        msg2:{
            type:String,
            default:""
        }
    })
    console.log(props) // { msg2:"這是傳級子組件的信息2" }
</script>

注意:

如果父組件是混合寫法,子組件純 Vue3 寫法的話,是接收不到父組件里 data 的屬性,只能接收到父組件里 setup 函數(shù)里傳的屬性

如果父組件是純 Vue3 寫法,子組件混合寫法,可以通過 props 接收到 data 和 setup 函數(shù)里的屬性,但是子組件要是在 setup 里接收,同樣只能接收到父組件中 setup 函數(shù)里的屬性,接收不到 data 里的屬性

官方也說了,既然用了 3,就不要寫 2 了,所以不推薦混合寫法。下面的例子,一律只用純 Vue3 的寫法,就不寫混合寫法了

$emit

// Child.vue 派發(fā)
<template>
    // 寫法一
    <button @click="emit('myClick')">按鈕</buttom>
    // 寫法二
    <button @click="handleClick">按鈕</buttom>
</template>
<script setup>
    
    // 方法一 適用于Vue3.2版本 不需要引入
    // import { defineEmits } from "vue"
    // 對應寫法一
    const emit = defineEmits(["myClick","myClick2"])
    // 對應寫法二
    const handleClick = ()=>{
        emit("myClick", "這是發(fā)送給父組件的信息")
    }
    
    // 方法二 不適用于 Vue3.2版本,該版本 useContext()已廢棄
    import { useContext } from "vue"
    const { emit } = useContext()
    const handleClick = ()=>{
        emit("myClick", "這是發(fā)送給父組件的信息")
    }
</script>

// Parent.vue 響應
<template>
    <child @myClick="onMyClick"></child>
</template>
<script setup>
    import child from "./child.vue"
    const onMyClick = (msg) => {
        console.log(msg) // 這是父組件收到的信息
    }
</script>

expose / ref

父組件獲取子組件的屬性或者調用子組件方法

// Child.vue
<script setup>
    // 方法一 不適用于Vue3.2版本,該版本 useContext()已廢棄
    import { useContext } from "vue"
    const ctx = useContext()
    // 對外暴露屬性方法等都可以
    ctx.expose({
        childName: "這是子組件的屬性",
        someMethod(){
            console.log("這是子組件的方法")
        }
    })
    
    // 方法二 適用于Vue3.2版本, 不需要引入
    // import { defineExpose } from "vue"
    defineExpose({
        childName: "這是子組件的屬性",
        someMethod(){
            console.log("這是子組件的方法")
        }
    })
</script>

// Parent.vue  注意 ref="comp"
<template>
    <child ref="comp"></child>
    <button @click="handlerClick">按鈕</button>
</template>
<script setup>
    import child from "./child.vue"
    import { ref } from "vue"
    const comp = ref(null)
    const handlerClick = () => {
        console.log(comp.value.childName) // 獲取子組件對外暴露的屬性
        comp.value.someMethod() // 調用子組件對外暴露的方法
    }
</script>

attrs

attrs:包含父作用域里除 class 和 style 除外的非 props 屬性集合

// Parent.vue 傳送
<child :msg1="msg1" :msg2="msg2" title="3333"></child>
<script setup>
    import child from "./child.vue"
    import { ref, reactive } from "vue"
    const msg1 = ref("1111")
    const msg2 = ref("2222")
</script>

// Child.vue 接收
<script setup>
    import { defineProps, useContext, useAttrs } from "vue"
    // 3.2版本不需要引入 defineProps,直接用
    const props = defineProps({
        msg1: String
    })
    // 方法一 不適用于 Vue3.2版本,該版本 useContext()已廢棄
    const ctx = useContext()
    // 如果沒有用 props 接收 msg1 的話就是 { msg1: "1111", msg2:"2222", title: "3333" }
    console.log(ctx.attrs) // { msg2:"2222", title: "3333" }
    
    // 方法二 適用于 Vue3.2版本
    const attrs = useAttrs()
    console.log(attrs) // { msg2:"2222", title: "3333" }
</script>

v-model

可以支持多個數(shù)據(jù)雙向綁定

// Parent.vue
<child v-model:key="key" v-model:value="value"></child>
<script setup>
    import child from "./child.vue"
    import { ref, reactive } from "vue"
    const key = ref("1111")
    const value = ref("2222")
</script>

// Child.vue
<template>
    <button @click="handlerClick">按鈕</button>
</template>
<script setup>
    
    // 方法一  不適用于 Vue3.2版本,該版本 useContext()已廢棄
    import { useContext } from "vue"
    const { emit } = useContext()
    
    // 方法二 適用于 Vue3.2版本,不需要引入
    // import { defineEmits } from "vue"
    const emit = defineEmits(["key","value"])
    
    // 用法
    const handlerClick = () => {
        emit("update:key", "新的key")
        emit("update:value", "新的value")
    }
</script>

provide / inject

provide / inject 為依賴注入

provide:可以讓我們指定想要提供給后代組件的數(shù)據(jù)或

inject:在任何后代組件中接收想要添加在這個組件上的數(shù)據(jù),不管組件嵌套多深都可以直接拿來用

// Parent.vue
<script setup>
    import { provide } from "vue"
    provide("name", "沐華")
</script>

// Child.vue
<script setup>
    import { inject } from "vue"
    const name = inject("name")
    console.log(name) // 沐華
</script>

Vuex

// store/index.js
import { createStore } from "vuex"
export default createStore({
    state:{ count: 1 },
    getters:{
        getCount: state => state.count
    },
    mutations:{
        add(state){
            state.count++
        }
    }
})

// main.js
import { createApp } from "vue"
import App from "./App.vue"
import store from "./store"
createApp(App).use(store).mount("#app")

// Page.vue
// 方法一 直接使用
<template>
    <div>{{ $store.state.count }}</div>
    <button @click="$store.commit('add')">按鈕</button>
</template>

// 方法二 獲取
<script setup>
    import { useStore, computed } from "vuex"
    const store = useStore()
    console.log(store.state.count) // 1

    const count = computed(()=>store.state.count) // 響應式,會隨著vuex數(shù)據(jù)改變而改變
    console.log(count) // 1 
</script>

Vue2.x 組件通信方式

Vue2.x 組件通信共有12種

  1. props
  2. $emit / v-on
  3. .sync
  4. v-model
  5. ref
  6. $children / $parent
  7. $attrs / $listeners
  8. provide / inject
  9. EventBus
  10. Vuex
  11. $root
  12. slot

父子組件通信可以用:

  • props
  • $emit / v-on
  • $attrs / $listeners
  • ref
  • .sync
  • v-model
  • $children / $parent

兄弟組件通信可以用:

  • EventBus
  • Vuex
  • $parent

跨層級組件通信可以用:

  • provide/inject
  • EventBus
  • Vuex
  • $attrs / $listeners
  • $root

Vue2.x 通信使用寫法

下面把每一種組件通信方式的寫法一一列出

1. props

父組件向子組件傳送數(shù)據(jù),這應該是最常用的方式了

子組件接收到數(shù)據(jù)之后,不能直接修改父組件的數(shù)據(jù)。會報錯,所以當父組件重新渲染時,數(shù)據(jù)會被覆蓋。如果子組件內要修改的話推薦使用 computed

// Parent.vue 傳送
<template>
    <child :msg="msg"></child>
</template>

// Child.vue 接收
export default {
  // 寫法一 用數(shù)組接收
  props:['msg'],
  // 寫法二 用對象接收,可以限定接收的數(shù)據(jù)類型、設置默認值、驗證等
  props:{
      msg:{
          type:String,
          default:'這是默認數(shù)據(jù)'
      }
  },
  mounted(){
      console.log(this.msg)
  },
}

2. .sync

可以幫我們實現(xiàn)父組件向子組件傳遞的數(shù)據(jù) 的雙向綁定,所以子組件接收到數(shù)據(jù)后可以直接修改,并且會同時修改父組件的數(shù)據(jù)

// Parent.vue
<template>
    <child :page.sync="page"></child>
</template>
<script>
export default {
    data(){
        return {
            page:1
        }
    }
}

// Child.vue
export default {
    props:["page"],
    computed(){
        // 當我們在子組件里修改 currentPage 時,父組件的 page 也會隨之改變
        currentPage {
            get(){
                return this.page
            },
            set(newVal){
                this.$emit("update:page", newVal)
            }
        }
    }
}
</script>

3. v-model

和 .sync 類似,可以實現(xiàn)將父組件傳給子組件的數(shù)據(jù)為雙向綁定,子組件通過 $emit 修改父組件的數(shù)據(jù)

// Parent.vue
<template>
    <child v-model="value"></child>
</template>
<script>
export default {
    data(){
        return {
            value:1
        }
    }
}

// Child.vue
<template>
    <input :value="value" @input="handlerChange">
</template>
export default {
    props:["value"],
    // 可以修改事件名,默認為 input
    model:{
        event:"updateValue"
    },
    methods:{
        handlerChange(e){
            this.$emit("input", e.target.value)
            // 如果有上面的重命名就是這樣
            this.$emit("updateValue", e.target.value)
        }
    }
}
</script>

4. ref

ref 如果在普通的DOM元素上,引用指向的就是該DOM元素;

如果在子組件上,引用的指向就是子組件實例,然后父組件就可以通過 ref 主動獲取子組件的屬性或者調用子組件的方法

// Child.vue
export default {
    data(){
        return {
            name:"沐華"
        }
    },
    methods:{
        someMethod(msg){
            console.log(msg)
        }
    }
}

// Parent.vue
<template>
    <child ref="child"></child>
</template>
<script>
export default {
    mounted(){
        const child = this.$refs.child
        console.log(child.name) // 沐華
        child.someMethod("調用了子組件的方法")
    }
}
</script>

5. $emit / v-on

子組件通過派發(fā)事件的方式給父組件數(shù)據(jù),或者觸發(fā)父組件更新等操作

// Child.vue 派發(fā)
export default {
  data(){
      return { msg: "這是發(fā)給父組件的信息" }
  },
  methods: {
      handleClick(){
          this.$emit("sendMsg",this.msg)
      }
  },
}
// Parent.vue 響應
<template>
    <child v-on:sendMsg="getChildMsg"></child>
    // 或 簡寫
    <child @sendMsg="getChildMsg"></child>
</template>

export default {
    methods:{
        getChildMsg(msg){
            console.log(msg) // 這是父組件接收到的消息
        }
    }
}

6. $attrs / $listeners

多層嵌套組件傳遞數(shù)據(jù)時,如果只是傳遞數(shù)據(jù),而不做中間處理的話就可以用這個,比如父組件向孫子組件傳遞數(shù)據(jù)時

$attrs:包含父作用域里除 class 和 style 除外的非 props 屬性集合。通過 this.$attrs 獲取父作用域中所有符合條件的屬性集合,然后還要繼續(xù)傳給子組件內部的其他組件,就可以通過 v-bind="$attrs"

$listeners:包含父作用域里 .native 除外的監(jiān)聽事件集合。如果還要繼續(xù)傳給子組件內部的其他組件,就可以通過 v-on="$linteners"

使用方式是相同的

// Parent.vue
<template>
    <child :name="name" title="1111" ></child>
</template
export default{
    data(){
        return {
            name:"沐華"
        }
    }
}

// Child.vue
<template>
    // 繼續(xù)傳給孫子組件
    <sun-child v-bind="$attrs"></sun-child>
</template>
export default{
    props:["name"], // 這里可以接收,也可以不接收
    mounted(){
        // 如果props接收了name 就是 { title:1111 },否則就是{ name:"沐華", title:1111 }
        console.log(this.$attrs)
    }
}

7. $children / $parent

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

$parent:獲取到一個父節(jié)點的 VueComponent 對象,同樣包含父節(jié)點中所有數(shù)據(jù)和方法等

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

// Child.vue
export default{
    mounted(){
        this.$parent.someMethod() // 調用父組件的方法
        this.$parent.name // 獲取父組件中的屬性
    }
}

8. provide / inject

provide / inject 為依賴注入,說是不推薦直接用于應用程序代碼中,但是在一些插件或組件庫里卻是被常用,所以我覺得用也沒啥,還挺好用的

provide:可以讓我們指定想要提供給后代組件的數(shù)據(jù)或方法

inject:在任何后代組件中接收想要添加在這個組件上的數(shù)據(jù)或方法,不管組件嵌套多深都可以直接拿來用

要注意的是 provide 和 inject 傳遞的數(shù)據(jù)不是響應式的,也就是說用 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ā)送自定義事件的組件內
<template>
    <button @click="handlerClick">按鈕</button>
</template>
import Bus from "./Bus.js"
export default{
    methods:{
        handlerClick(){
            // 自定義事件名 sendMsg
            Bus.$emit("sendMsg", "這是要向外部發(fā)送的數(shù)據(jù)")
        }
    }
}

// 在需要接收外部事件的組件內
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")
    }
}

10. Vuex

Vuex 是狀態(tài)管理器,集中式存儲管理所有組件的狀態(tài)。這一塊內容過長,如果基礎不熟的話可以看這個Vuex,然后大致用法如下

比如創(chuàng)建這樣的文件結構

index.js 里內容如下

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ù)和方法

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>

結語

寫作不易,你的一贊一評,就是我前行的最大動力。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,197評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,415評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,104評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,884評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,647評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,130評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,208評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,366評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 48,887評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,737評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,939評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,478評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,174評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,586評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,827評論 1 283
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,608評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,914評論 2 372

推薦閱讀更多精彩內容