>[success] # 組件通信(三)
~~~
1.了解'$on'與'$emit'
2.根據Vue.js 1.x 的 '$dispatch' 與 '$broadcast' 兩方法思路偽造一個,
屬于vue.js 2.x 系列同樣的方法.其中 '$dispatch'子傳父或者孫子傳爺爺,
'$broadcast' 則相反,但是只會找到最近的觸發
~~~
>[info] ## 了解 '$on'與'$emit'
~~~
1.使用 $on(eventName) 監聽事件第二個參數是個方法,
使用 $emit(eventName) 觸發事件第二個參數是傳值,
這兩個方法常見的使用場景就是'bus'
2.要注意 '$on' 監聽需要在 mounted 或 created 鉤子中來監聽。
3.可以參考筆者另一個筆記內容'前端知識 -- 學習整理',這個思路就是設計
模式中的'發布訂閱'模式
~~~
>[danger] ##### 不是只有bus 才能用
~~~
1.$on 監聽了自己觸發的自定義事件 test,因為有時不確定何時會觸發事件,
一般會在 mounted 或 created 鉤子中來監聽。
~~~
* 自己觸發自己的$emit 和 $on,下面寫法多此一舉建議直接handleEmitEvent觸發alter
~~~
<template>
<div>
<button @click="handleEmitEvent">觸發自定義事件</button>
</div>
</template>
<script>
export default {
methods: {
handleEmitEvent () {
// 在當前組件上觸發自定義事件 test,并傳值
this.$emit('test', 'Hello Vue.js')
}
},
mounted () {
// 監聽自定義事件 test
this.$on('test', (text) => {
window.alert(text);
});
}
}
</script>
~~~
* 運行效果

>[info] ## 自定義 dispatch 和 broadcast 方法 思路
~~~
1.在vue1.x 中'$dispatch' 是子孫組件向父爺組件傳遞,'broadcast '則相反,
但是只會找到最近的觸發
2.兩者都是使用'$on' 觸發
~~~
>[danger] ##### 定義前看一下vue1.x版本使用
~~~
1.在這里 還要強調說明監聽的'$on'要在 mounted 或 created 鉤子中來監聽。
~~~
* 在子組件定義
~~~
<!-- 注意:該示例為 Vue.js 1.x 版本 -->
<!-- 子組件 -->
<template>
<button @click="handleDispatch">派發事件</button>
</template>
<script>
export default {
methods: {
handleDispatch () {
this.$dispatch('test', 'Hello, Vue.js');
}
}
}
</script>
~~~
* 在父組件中使用
~~~
<!-- 父組件,部分代碼省略 -->
<template>
<child-component></child-component>
</template>
<script>
export default {
mounted () {
this.$on('test', (text) => {
console.log(text); // Hello, Vue.js
});
}
}
</script>
~~~
>[danger] ##### 封裝思路
~~~
1.通過上面1.x案例可以看出來,大體上需要兩個參數一個是觸發的事件名字,一個是傳
遞的參數,但是我們自定義的需要使用一個標記參數,來找到我們需要匹配的組件,如何
找這里就利用創建組件的使用name屬性如下圖
~~~

>[info] ## 正式封裝
~~~
1.思路其實就是利用 '$on' 和 '$emit' 配合,通過我們自己寫的這個方法,讓對應
要調用的父組件或者子組件,this指向他本身,這樣形成給其自身加入對應的方法,
但可以有子組件或父組件的傳值
2.首先明確一點'$emit' 和 '$on' 是典型的發布的訂閱模式,'$on'通過訂閱的方式,來接受'$emit'
發布的內容,當然他的發布和訂閱 必須是同一個'this',因此利用vue自帶的'$parent' 和'$children'
從父組件開始找也好,從子組件開始找也好,原理就是層級向上找讓彼此可以發布訂閱在一起
~~~
代碼參考[iView](https://link.juejin.im/?target=https%3A%2F%2Fgithub.com%2Fiview%2Fiview%2Fblob%2F2.0%2Fsrc%2Fmixins%2Femitter.js)。
>[danger] ##### 從子組件傳遞給父組件甚至爺爺組件
~~~
1.獲取當前組件的'parent',因為剛才構想過,我們需要傳遞三個參數,其中一個參數要匹配
的目標組件名字,因此邏輯就是去找'parent' 和要匹配的名字是否一致,找到符合的'parent'
給這個父組件添加'$emit'事件,在這個父組件中使用'$on' 去觸發
~~~
~~~
// 子傳父,孫子傳爺爺或者爸爸
/*
* @params:componentName 對應組件名 ,eventName 事件名稱,params 函數參數
* */
dispatch(componentName, eventName, params) {
let parent = this.$parent || this.$root;
let name = parent.$options.name;
console.log(this.$options)
console.log(this.$options.name)
// 遞歸一層一層找
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
// 有父組件名稱 在去找組件name,如果沒有了 就不用特意去找
if (parent) {
name = parent.$options.name;
}
}
if (parent) {
parent.$emit(parent, [eventName].concat(params));
// parent.$emit(eventName,params);
}
},
~~~
>[danger] ##### 從爺爺組件給孫子組件,父傳子
~~~
1.思路就找每一個children,找到是否 有和名字匹配的并且綁上$emit()事件
~~~
~~~
function broadcast(componentName, eventName, params) {
this.$children.forEach(child => {
const name = child.$options.name;
if (name === componentName) {
child.$emit.apply(child, [eventName].concat(params));
} else {
broadcast.apply(child, [componentName, eventName].concat([params]));
}
});
}
~~~
>[danger] ##### 將所有代碼放到mixins進行存儲使用(最后的封裝)
~~~
function broadcast(componentName, eventName, params) {
// 當前的this 指向是在methods broadcast 中被改變了
// 因此現在的this 是每一個組件的this
this.$children.forEach(child => {
const name = child.$options.name;
if (name === componentName) {
child.$emit.apply(child, [eventName].concat(params));
} else {
// 遞歸 更改新的this,獲取新的組件中的children,也就是更新成當前父組件的this
broadcast.apply(child, [componentName, eventName].concat([params]));
}
});
}
export default {
methods: {
// 子傳父,孫子傳爺爺或者爸爸
/*
* @params:componentName 對應組件名 ,eventName 事件名稱,params 函數參數
* */
dispatch(componentName, eventName, params) {
let parent = this.$parent || this.$root;
let name = parent.$options.name;
console.log(this.$options)
console.log(this.$options.name)
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
// 有父組件名稱 在去找組件name,如果沒有了 就不用特意去找
if (parent) {
name = parent.$options.name;
}
}
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params));
// parent.$emit(eventName,params);
}
},
broadcast(componentName, eventName, params) {
// 當前this 也就是其中的父組件 有了broadcast方法
broadcast.call(this, componentName, eventName, params);
}
}
};
~~~
>[danger] ##### 使用
~~~
1.要注意'$on' 要放到mounted 或 created 去使用
~~~
* 父組件
~~~
<!-- A.vue -->
<template>
<div>
<button @click="handleClick">觸發事件</button>
<my-button class="aaa" id="222" index="666"></my-button>
</div>
</template>
<script>
import Emitter from '../mixins/emitter.js';
import MyButton from '@/components/MyButton'
export default {
name: 'componentA',
mixins: [ Emitter ],
methods: {
handleClick () {
// 父傳子
this.broadcast('componentB', 'on-message', 'Hello Vue.js');
},
},
created(){
// 子傳父接受
this.$on('test', (val)=>{
console.log(val)
})
},
components:{
MyButton
}
}
</script>
~~~
* 子組件
~~~
<template>
<div index="987">
<button @click="clickToPranent">點擊</button>
</div>
</template>
<script>
import Emitter from '@/mixins/emitter';
export default {
inheritAttrs: false,
name: 'componentB',
// 使用封裝
mixins: [ Emitter ],
created () {
// 接收父傳子
this.$on('on-message', this.showMessage);
},
methods: {
showMessage (text) {
console.log(1)
window.alert(text);
},
clickToPranent(){
// 調用子傳父
this.dispatch('componentA','test','aaa')
},
}
}
</script>
<style scoped>
</style>
~~~
- Vue--基礎篇章
- Vue -- 介紹
- Vue -- MVVM
- Vue -- 創建Vue實例
- Vue -- 模板語法
- Vue -- 指令用法
- v-cloak -- 遮蓋
- v-bind -- 標簽屬性動態綁定
- v-on -- 綁定事件
- v-model -- 雙向數據綁定
- v-for -- 只是循環沒那么簡單
- 小知識點 -- 計劃內屬性
- key -- 屬性為什么要加
- 案例說明
- v-if/v-show -- 顯示隱藏
- v-for 和 v-if 同時使用
- v-pre -- 不渲染大大胡語法
- v-once -- 只渲染一次
- Vue -- class和style綁定
- Vue -- filter 過濾器
- Vue--watch/computed/fun
- watch -- 巧妙利用watch思想
- Vue -- 自定義指令
- Vue -- $方法
- Vue--生命周期
- Vue -- 專屬ajax
- Vue -- transition過渡動畫
- 前面章節的案例
- 案例 -- 跑馬燈效果
- 案例 -- 選項卡內容切換
- 案例-- 篩選商品
- 案例 -- 搜索/刪除/更改
- 案例 -- 用computed做多選
- 案例 -- checked 多選
- Vue--組件篇章
- component -- 介紹
- component -- 使用全局組件
- component -- 使用局部組件
- component -- 組件深入
- component -- 組件傳值父傳子
- component -- 組件傳值子傳父
- component -- 子傳父語法糖拆解
- component -- 父組件操作子組件
- component -- is 動態切換組件
- component -- 用v-if/v-show控制子組件
- component -- 組件切換的動畫效果
- component -- slot 插槽
- component -- 插槽2.6
- component -- 組件的生命周期
- component -- 基礎組件全局注冊
- VueRouter--獲取路由參數
- VueRouter -- 介紹路由
- VueRouter -- 安裝
- VueRouter -- 使用
- VueRouter--router-link簡單參數
- VueRouter--router-link樣式問題
- VueRouter--router-view動畫效果
- VueRouter -- 匹配優先級
- vueRouter -- 動態路由
- VueRouter -- 命名路由
- VueRouter -- 命名視圖
- VueRouter--$router 獲取函數
- VueRouter--$route獲取參數
- VueRouter--路由嵌套
- VueRouter -- 導航守衛
- VueRouter -- 寫在最后
- Vue--模塊化方式結構
- webpack--自定義配置
- webpack -- 自定義Vue操作
- VueCli -- 3.0可視化配置
- VueCli -- 3.0 項目目錄
- Vue -- 組件升級篇
- Vue -- 組件種類與組件組成
- Vue -- 組件prop、event、slot 技巧
- Vue -- 組件通信(一)
- Vue -- 組件通信(二)
- Vue -- 組件通信(三)
- Vue -- 組件通信(四)
- Vue -- 組件通信(五)
- Vue -- 組件通信(六)
- Vue -- bus非父子組件通信
- Vue -- 封裝js插件成vue組件
- vue組件分裝 -- 進階篇
- Vue -- 組件封裝splitpane(分割面板)
- UI -- 正式封裝
- Vue -- iview 可編輯表格案例
- Ui -- iview 可以同時編輯多行
- Vue -- 了解遞歸組件
- UI -- 正式使用遞歸菜單
- Vue -- iview Tree組件
- Vue -- 利用通信仿寫一個form驗證
- Vue -- 使用自己的Form
- Vue -- Checkbox 組件
- Vue -- CheckboxGroup.vue
- Vue -- Alert 組件
- Vue -- 手動掛載組件
- Vue -- Alert開始封裝
- Vue -- 動態表單組件
- Vue -- Vuex組件的狀態管理
- Vuex -- 參數使用理解
- Vuex -- state擴展
- Vuex -- getters擴展
- Vuex--mutations擴展
- Vuex -- Action 異步
- Vuex -- plugins插件
- Vuex -- v-model寫法
- Vuex -- 更多
- VueCli -- 技巧總結篇
- CLI -- 路由基礎
- CLI -- 路由升級篇
- CLI --異步axios
- axios -- 封裝axios
- CLI -- 登錄寫法
- CLI -- 權限
- CLI -- 簡單權限
- CLI -- 動態路由加載
- CLI -- 數據性能優化
- ES6 -- 類的概念
- ES6類 -- 基礎
- ES6 -- 繼承
- ES6 -- 工作實戰用類數據管理
- JS -- 適配器模式
- ES7 -- 裝飾器(Decorator)
- 裝飾器 -- 裝飾器修飾類
- 裝飾器--修飾類方法(知識擴展)
- 裝飾器 -- 裝飾器修飾類中的方法
- 裝飾器 -- 執行順序
- Reflect -- es6 自帶版本
- Reflect -- reflect-metadata 版本
- 實戰 -- 驗證篇章(基礎)
- 驗證篇章 -- 搭建和目錄
- 驗證篇章 -- 創建基本模板
- 驗證篇章 -- 使用
- 實戰 -- 更新模型(為了迎合ui升級)
- 實戰 -- 模型與接口對接
- TypeSprict -- 基礎篇章
- TS-- 搭建(一)webpack版本
- TS -- 搭建(二)直接使用
- TS -- 基礎類型
- TS -- 枚舉類型
- TS -- Symbol
- TS -- interface 接口
- TS -- 函數
- TS -- 泛型
- TS -- 類
- TS -- 類型推論和兼容
- TS -- 高級類型(一)
- TS -- 高級類型(二)
- TS -- 關于模塊解析
- TS -- 聲明合并
- TS -- 混入
- Vue -- TS項目模擬
- TS -- vue和以前代碼對比
- TS -- vue簡單案例上手
- Vue -- 簡單弄懂VueRouter過程
- VueRouter -- 實現簡單Router
- Vue-- 原理2.x源碼簡單理解
- 了解 -- 簡單的響應式工作原理
- 準備工作 -- 了解發布訂閱和觀察者模式
- 了解 -- 響應式工作原理(一)
- 了解 -- 響應式工作原理(二)
- 手寫 -- 簡單的vue數據響應(一)
- 手寫 -- 簡單的vue數據響應(二)
- 模板引擎可以做的
- 了解 -- 虛擬DOM
- 虛擬dom -- 使用Snabbdom
- 閱讀 -- Snabbdom
- 分析snabbdom源碼 -- h函數
- 分析snabbdom -- init 方法
- init 方法 -- patch方法分析(一)
- init 方法 -- patch方法分析(二)
- init方法 -- patch方法分析(三)
- 手寫 -- 簡單的虛擬dom渲染
- 函數表達解析 - h 和 create-element
- dom操作 -- patch.js
- Vue -- 完成一個minVue
- minVue -- 打包入口
- Vue -- new實例做了什么
- Vue -- $mount 模板編譯階段
- 模板編譯 -- 分析入口
- 模板編譯 -- 分析模板轉譯
- Vue -- mountComponent 掛載階段
- 掛載階段 -- vm._render()
- 掛載階段 -- vnode
- 備份章節
- Vue -- Nuxt.js
- Vue3 -- 學習
- Vue3.x --基本功能快速預覽
- Vue3.x -- createApp
- Vue3.x -- 生命周期
- Vue3.x -- 組件
- vue3.x -- 異步組件???
- vue3.x -- Teleport???
- vue3.x -- 動畫章節 ??
- vue3.x -- 自定義指令 ???
- 深入響應性原理 ???
- vue3.x -- Option API VS Composition API
- Vue3.x -- 使用set up
- Vue3.x -- 響應性API
- 其他 Api 使用
- 計算屬性和監聽屬性
- 生命周期
- 小的案例(一)
- 小的案例(二)-- 泛型
- Vue2.x => Vue3.x 導讀
- v-for 中的 Ref 數組 -- 非兼容
- 異步組件
- attribute 強制行為 -- 非兼容
- $attrs 包括 class & style -- 非兼容
- $children -- 移除
- 自定義指令 -- 非兼容
- 自定義元素交互 -- 非兼容
- Data選項 -- 非兼容
- emits Option -- 新增
- 事件 API -- 非兼容
- 過濾器 -- 移除
- 片段 -- 新增
- 函數式組件 -- 非兼容
- 全局 API -- 非兼容
- 全局 API Treeshaking -- 非兼容
- 內聯模板 Attribute -- 非兼容
- key attribute -- 非兼容
- 按鍵修飾符 -- 非兼容
- 移除 $listeners 和 v-on.native -- 非兼容
- 在 prop 的默認函數中訪問 this -- ??
- 組件使用 v-model -- 非兼容
- 渲染函數 API -- ??
- Slot 統一 ??
- 過渡的 class 名更改 ???
- Transition Group 根元素 -- ??
- v-if 與 v-for 的優先級對比 -- 非兼容
- v-bind 合并行為 非兼容
- 監聽數組 -- 非兼容