本篇博客所有的代碼均在github上: https://github.com/zuxian/
總結
- 父子通信:
父向子傳遞數據是通過props
,子向父是通過 events($emit)
;
通過父鏈 / 子鏈也可以通信($parent / $children)
;
$ref
也可以訪問組件實例;
provide / inject API
;
$attrs/$listeners
- 兄弟通信:
Bus;Vuex
- 跨級通信:
Bus;Vuex;provide / inject API、$attrs/$listeners
1,父 ==> 子(props)
2,子 ==> 父(emit自定義事件)
3,非父子組件通信(EventBus) ---`$emit、 $on 、$off`
組件APP.vue (同時引入Hello.vue組件和World.vue組件)
methods: { sendParam () { bus.$emit('getParam', this.number) } }
created () { bus.$on('getParam', param => { this.number = param }) },
beforeDestroy () { bus.$off('getParam') }
- bus.js
import Vue from 'vue'
const bus = new Vue();
export default bus
-
組件Hello.vue
-
組件World.vue
-
組件APP.vue (同時引入Hello.vue組件和World.vue組件)
4,$ref
- ref:
如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;
如果用在子組件上,引用就指向組件實例
compA.vue
APP.vue
5,祖 ==> 孫(provide/inject)
vue提供了provide和inject幫助我們解決多層次嵌套嵌套通信問題。
在provide中指定要傳遞給子孫組件的數據,子孫組件通過inject注入祖父組件傳遞過來的數據。
6,跨級組件 `$attrs與$listeners`
-
$attrs
:包含了父作用域中不被 prop 所識別 (且獲取) 的特性綁定 (class 和 style 除外)。當一個組件沒有聲明任何 prop 時,這裏會包含所有父作用域的綁定 (class 和 style 除外),並且可以通過 v-bind="$attrs" 傳入內部組件。通常配合 interitAttrs 選項一起使用。
-
$listeners
:包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監聽器。它可以通過 v-on="$listeners" 傳入內部組件
-
- inheritAttrs:默認值true,繼承所有的父組件屬性(除props的特定綁定)作爲普通的HTML特性應用在子組件的根元素上,如果你不希望組件的根元素繼承特性設置inheritAttrs: false,但是class屬性會繼承(簡單的說,inheritAttrs:true 繼承除props之外的所有屬性;inheritAttrs:false 只繼承class屬性)
-
APP.vue
-
Child1.vue
-
Child2.vue
- 結果: