前言
本章總結(jié)了vue2.x與vue3.x的通信方式
VUE2.x的通信方式
-
props傳遞數(shù)據(jù) - 通過
$emit觸發(fā)自定義事件 - 使用
$ref - 作用域插槽(
slot) eventBus-
$parent(或$root)與$children -
$attrs與$listeners -
provide與inject Vuex
適合父子間通信:props、$emit、$ref、slot、$parent、$children
適合兄弟組件之間的通信:eventBus、Vuex
祖孫與后代組件之間的通信:$attrs/$listeners、provide/inject、eventBus、Vuex
復(fù)雜關(guān)系的組件之間的通信:Vuex
1. props傳遞數(shù)據(jù)
- 適用場景:父組件傳遞數(shù)據(jù)給子組件
- 使用方式:
????????子組件設(shè)置props屬性,定義接收父組件傳遞過來的參數(shù)
????????父組件在使用子組件標(biāo)簽中通過字面量來傳遞值
// 父組件
<Children name="jack" age=18 />
// 子組件
props:{
name:String // 接收的類型參數(shù)
age:{
type:Number, // 接收的類型為數(shù)值
defaule:18 // 默認(rèn)值為18
}
}
2. $emit 觸發(fā)自定義事件
- 適用場景:子組件傳遞數(shù)據(jù)給父組件
- 使用方式:
????????子組件通過$emit觸發(fā)自定義事件,$emit第二個參數(shù)為傳遞的數(shù)值
????????父組件綁定監(jiān)聽器獲取到子組件傳遞過來的參數(shù)
// 父組件
<Children @add="cartAdd" />
// 子組件
this.$emit('add', 'good')
3. ref
- 適用場景:父組件需要獲取到子組件時
- 使用方式:
????????父組件在使用子組件的時候設(shè)置ref
????????父組件通過設(shè)置子組件ref來獲取數(shù)據(jù)
// 父組件
<Children ref="foo" />
this.$refs.foo // 獲取子組件實例,通過子組件實例我們就能拿到對應(yīng)的數(shù)據(jù)及函數(shù)
4. 作用域插槽(slot)
5. EventBus
- 適用場景:兄弟組件/隔代組件之間的通信
- 使用方式:
????????創(chuàng)建一個中央時間總線EventBus
????????一個組件通過$on監(jiān)聽自定義事件
????????另一個組件通過$emit觸發(fā)事件,$emit第二個參數(shù)為傳遞的數(shù)值
// 創(chuàng)建一個中央時間總線類
class Bus {
constructor() {
this.callbacks = {}; // 存放事件的名字
}
$on(name, fn) {
this.callbacks[name] = this.callbacks[name] || [];
this.callbacks[name].push(fn);
}
$emit(name, args) {
if (this.callbacks[name]) {
this.callbacks[name].forEach((cb) => cb(args));
}
}
}
// main.js
Vue.prototype.$bus = new Bus() // 將$bus掛載到vue實例的原型上
// 一個組件監(jiān)聽自定義事件
this.$bus.$on('foo', function() {});
// 另一個組件觸發(fā)事件
this.$bus.$emit('foo')
6. $parent 或$root與$children
- 適用場景:通過共同祖輩parent或者root搭建通信僑聯(lián)
- 兄弟組件之間:
// 兄弟組件
this.$parent.on('add',this.add);
// 另一個兄弟組件
this.$parent.emit('add');
- 父子組件之間:
// 子組件獲取到子組件
this.$parent
// 同理,父組件獲取到子組件,但是是個列表
this.$children

7. $attrs 與 $listeners
- 適用場景:祖先傳遞屬性(可以是值,可以是函數(shù))給子孫
-
$attrs:包含了父作用域中不被認(rèn)為 (且不預(yù)期為) props 的特性綁定 (class 和 style 除外),并且可以通過v-bind=”$attrs”傳入內(nèi)部組件。當(dāng)一個組件沒有聲明任何 props 時,它包含所有父作用域的綁定 (class 和 style 除外)。 -
$listeners:包含了父作用域中的 (不含 .native 修飾符) v-on 事件監(jiān)聽器。它可以通過v-on=”$listeners”傳入內(nèi)部組件。它是一個對象,里面包含了作用在這個組件上的所有事件監(jiān)聽器,相當(dāng)于子組件繼承了父組件的事件。
<!-- father.vue 組件:-->
<template>
<child :name="name" :age="age" :infoObj="infoObj" @updateInfo="updateInfo" @delInfo="delInfo" />
</template>
<script>
import Child from '../components/child.vue'
export default {
name: 'father',
components: { Child },
data () {
return {
name: 'Lily',
age: 22,
infoObj: {
from: '上海',
job: 'policeman',
hobby: ['reading', 'writing', 'skating']
}
}
},
methods: {
updateInfo() {
console.log('update info');
},
delInfo() {
console.log('delete info');
}
}
}
</script>
<!-- child.vue 組件:-->
<template>
<grand-son :height="height" :weight="weight" @addInfo="addInfo" v-bind="$attrs" v-on="$listeners" />
// 通過 $listeners 將父作用域中的事件,傳入 grandSon 組件,使其可以獲取到 father 中的事件
</template>
<script>
import GrandSon from '../components/grandSon.vue'
export default {
name: 'child',
components: { GrandSon },
props: ['name'],
data() {
return {
height: '180cm',
weight: '70kg'
};
},
created() {
console.log(this.$attrs);
// 結(jié)果:age, infoObj, 因為父組件共傳來name, age, infoObj三個值,由于name被 props接收了,所以只有age, infoObj屬性
console.log(this.$listeners); // updateInfo: f, delInfo: f
},
methods: {
addInfo () {
console.log('add info')
}
}
}
</script>
<!-- grandSon.vue 組件:-->
<template>
<div>
{{ $attrs }} --- {{ $listeners }}
<div>
</template>
<script>
export default {
... ...
props: ['weight'],
created() {
console.log(this.$attrs); // age, infoObj, height
console.log(this.$listeners) // updateInfo: f, delInfo: f, addInfo: f
this.$emit('updateInfo') // 可以觸發(fā)隔代組件father中的updateInfo函數(shù)
}
}
</script>
簡易版例子:
// 給Grandson隔代傳值,communication/index.vue
<Child2 msg="lalala" @some-event="onSomeEvent"></Child2>
// Child2做展開
<Grandson v-bind="$attrs" v-on="$listeners"></Grandson>
// Grandson使?
<div @click="$emit('some-event', 'msg from grandson')">
{{msg}}
</div>
8. provide 與 inject
- 適用場景:祖先傳遞值給子孫
// 祖先組件
provide(){
return {
foo:'foo'
}
}
// 后代組件
inject:['foo'] // 獲取到祖先組件傳遞過來的值
9. vuex
- 適用場景: 復(fù)雜關(guān)系的組件數(shù)據(jù)傳遞
- Vuex作用相當(dāng)于一個用來存儲共享變量的容器
state:包含了store中存儲的各個狀態(tài)。
getter: 類似于 Vue 中的計算屬性,根據(jù)其他 getter 或 state 計算返回值。
mutation: 一組方法,是改變store中狀態(tài)的執(zhí)行者,只能是同步操作。
action: 一組方法,其中可以包含異步操作。

// main.js
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0,
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getter: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
increment (state, payload) {
state.count++
}
},
actions: {
addCount(context) {
// 可以包含異步操作
// context 是一個與 store 實例具有相同方法和屬性的 context 對象
}
}
})
// 注入到根實例
new Vue({
el: '#app',
// 把 store 對象提供給 “store” 選項,這可以把 store 的實例注入所有的子組件
store,
template: '<App/>',
components: { App }
});
// 在子組件中使用
// 創(chuàng)建一個 Counter 組件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
},
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
}
VUE3.0的通信方式
-
props傳遞數(shù)據(jù) - 通過
emit觸發(fā)自定義事件 - 使用
ref - 作用域插槽(
slot) -
mitt()eventBus -
$parent(或$root)與$children -
$attrs與$listeners -
provide與inject Vuex
適合父子間通信:props、emit、ref、slot、parent、children
適合兄弟組件之間的通信:mitt()、eventBusVuex
祖孫與后代組件之間的通信:$attrs/$listeners、provide/inject、mitt()、eventBusVuex
復(fù)雜關(guān)系的組件之間的通信:Vuex
1. props傳遞數(shù)據(jù)
- 適用場景:父組件向子組件傳遞數(shù)據(jù)
- 使用方式:
????????父組件在使用子組件標(biāo)簽中通過字面量來傳遞值(與VUE2.x方式相同)
????????與VUE2.x相同的是子組件也設(shè)置props屬性配置接受的數(shù)據(jù),不同的是vue3.0的prop為setup的第一個參數(shù)
// 父組件
<child msg="hello"/>
// 子組件
export default defineComponent({
props: { // 配置要接受的props
msg: {
type: String,
default: () => ''
}
},
setup(props) {
console.log('props ====', props);
},
});

2. emit 觸發(fā)自定義事件
- 適用場景:子組件傳遞數(shù)據(jù)給父組件
- 使用方式:
????????父組件綁定監(jiān)聽器獲取到子組件傳遞過來的參數(shù)(與VUE2.x方式相同)
????????與VUE2.x不同的是:子組件通過context.emit觸發(fā)自定義事件(context為setup的第二個參數(shù),為上下文),相同的是:emit第二個參數(shù)為傳遞的數(shù)值
<!-- Father.vue -->
<template>
<div style="width: 500px; height: 500px; padding: 20px; border: 2px solid #ff00ff;">
<div>Father:</div>
<child msg="hello" @todoSth="todoSth"/>
</div>
</template>
<script lang="ts">
import {
defineComponent
} from 'vue';
import child from './components/child.vue';
export default defineComponent({
components: {
child
},
setup() {
// 父組件綁定監(jiān)聽器獲取到子組件傳遞過來的參數(shù)
const todoSth = (text: string) => {
console.log('text: ', text);
};
return {
todoSth
};
},
});
</script>
<!-- Child.vue -->
<template>
<div style="width: 100%; height: calc(100% - 40px); padding: 20px; box-sizing: border-box; border: 2px solid #00ff00;">
<div>Child:</div>
<button @click="setMsg2Parent">點擊按鈕給父組件傳遞信息</button>
</div>
</template>
<script lang="ts">
import {
defineComponent
} from 'vue';
export default defineComponent({
setup(props, context) {
const setMsg2Parent = () => {
context.emit('todoSth', 'hi parent!');
};
return {
setMsg2Parent
};
},
});
</script>

3. ref
- 適用場景:父組件需要獲取到子組件時
- 使用方式:
????????父組件在使用子組件的時候設(shè)置ref(與VUE2.x方式相同)
????????父組件通過設(shè)置子組件ref來獲取數(shù)據(jù)
注:: 1.獲取子組件時變量名必須與子組件的ref屬性保持一致;2.必須將獲取到的組件return。
<!-- Father.vue -->
<template>
<div style="width: 500px; height: 500px; padding: 20px; border: 2px solid #ff00ff;">
<div>Father:</div>
<button @click="getChildCom">獲取到子組件并調(diào)用其屬性</button>
<child ref="childCom" msg="hello"/>
</div>
</template>
<script lang="ts">
import {
defineComponent,
ref
} from 'vue';
import child from './components/child.vue';
export default defineComponent({
components: {
child
},
setup() {
const childCom = ref<HTMLElement>(null);
// 獲取到子組件并調(diào)用其屬性
const getChildCom = () => {
childCom.value.childText = '父組件想要改變這個屬性!';
childCom.value.childMethod1();
};
return {
childCom,
getChildCom
};
},
});
</script>
<!-- Child.vue -->
<template>
<div style="width: 100%; height: calc(100% - 40px); padding: 20px; box-sizing: border-box; border: 2px solid #00ff00;">
<div>Child:</div>
<p>{{childText}}</p>
</div>
</template>
<script lang="ts">
import {
defineComponent,
reactive,
toRefs
} from 'vue';
export default defineComponent({
props: {
msg: {
type: String,
default: () => ''
}
},
setup(props, context) {
const currStatus = reactive({
childText: '我是一個子組件~~~'
});
const childMethod1 = () => {
console.log('這是子組件的一個方法');
};
return {
childMethod1,
...toRefs(currStatus)
};
},
});
</script>

事件調(diào)用前

事件調(diào)用后
4. 作用域插槽(slot)
5. mitt
- 適用場景:兄弟組件/隔代組件之間的通信
- Vue 3 移除了
$on、$off和$once這幾個事件 API ,應(yīng)用實例不再實現(xiàn)事件觸發(fā)接口。 - 根據(jù)官方文檔在 遷移策略 - 事件 API 的推薦,我們可以用 mitt 或者 tiny-emitter 等第三方插件來實現(xiàn)
EventBus。
6. $parent 或$root與$children
- 適用場景:通過共同祖輩parent或者root搭建通信僑聯(lián)
-
$children已被廢棄 -
$parent使用方式與vue2.x有所區(qū)別($root同理)
| vue2.0 | vue3.0 |
|---|---|
| this.$parent.父組件的方法名/父組件的屬性名 | import {getCurrentInstance} from 'vue'; const {proxy} = getCurrentInstance(); proxy.$parent.父組件的方法名/父組件的屬性名 |
7. $attrs 與 $listeners
- 適用場景:祖先傳遞屬性(可以是值,可以是函數(shù))給子孫
- 使用方式與vue2.0一致
-
$attrs:包含了父作用域中不被認(rèn)為 (且不預(yù)期為) props 的特性綁定 (class 和 style 除外),并且可以通過v-bind=”$attrs”傳入內(nèi)部組件。當(dāng)一個組件沒有聲明任何 props 時,它包含所有父作用域的綁定 (class 和 style 除外)。 -
$listeners:包含了父作用域中的 (不含 .native 修飾符) v-on 事件監(jiān)聽器。它可以通過v-on=”$listeners”傳入內(nèi)部組件。它是一個對象,里面包含了作用在這個組件上的所有事件監(jiān)聽器,相當(dāng)于子組件繼承了父組件的事件。
<!-- Father.vue -->
<child msg="hello" attrsText="測試attrsText" @listenersFun="listenersFun"/>
export default defineComponent({
components: {
child
},
setup(props, context) {
const listenersFun = (msg: string) => {
console.log(msg);
}
return {
listenersFun
};
},
});
<!-- Child.vue -->
<grandsun v-bind="$attrs" v-on="$listeners"/>
export default defineComponent({
components: {
grandsun
},
// 子組件的props沒有配置attrsText,故attrsText存在context.attrs中
props: {
msg: {
type: String,
default: () => ''
}
},
});
<!-- Grandsun.vue -->
export default defineComponent({
setup(props, context) {
console.log('通過attrs獲取祖父的屬性值:', context.attrs.attrsText)
context.emit('listenersFun', '通過listeners跨級調(diào)用祖父的函數(shù)');
},
});

8. provide 與 inject
- 適用場景:祖先傳遞值給子孫
- 使用方式與vue2.0略有差異,vue2.0的provide和inject都為配置項,而在 3.x , provide 需要導(dǎo)入并在 setup 里啟用,并且現(xiàn)在是一個全新的方法。在 3.x , provide 需要導(dǎo)入并在 setup 里啟用,并且現(xiàn)在是一個全新的方法。
// father.vue
import { provide } from 'vue';
// provide出去(key, value)
provide('msg', '祖父傳遞一個屬性給子孫');
// Grandsun.vue
import { inject } from 'vue';
console.log('通過inject獲取祖父的屬性值:', inject('msg'))
參考:
https://segmentfault.com/a/1190000022708579
https://juejin.cn/post/6844903990052782094#heading-0
https://vue3.chengpeiquan.com/communication.html#%E7%88%B6%E5%AD%90%E7%BB%84%E4%BB%B6%E9%80%9A%E4%BF%A1
https://blog.csdn.net/qq_15601471/article/details/122032034