你們或許都據說EventBus,或者說或多或少都瞭解過,他能夠在任何兩個組件中進行傳值,不侷限於父子、祖孫或是兄弟組件,也能夠說他是一種發佈——訂閱的設計模式。vue
但您是否真正的會熟練的使用他嗎?vue-router
本文將把一個例子拆分步驟,讓讀者能真的明白EventBus到底如何使用!vue-cli
我將使用拆分爲五個步驟:建立、引入、監聽、遞交、銷燬設計模式
Vue中自帶EventBus,不須要額外任何使用插件markdown
只須要new一個「vue實例」ui
像這樣~this
// 建立一個EventBus.js文件
import Vue from 'vue' // 引入vue
const EventBus = new Vue() // 建立實例
export default EventBus // 導出
複製代碼
引入的方式有兩種spa
這個方法特別須要注意的是應該引入 同一個實例prototype
import EventBus from '../EventBus'
複製代碼
若是您和我同樣用的是 vue-cli 腳手架插件
能夠直接在Vue的原型鏈上添加全局方法
// 在 src 的 main.js 中,加上如下代碼
// 引入第一步建立好的 EventBus
import EventBus from './EventBus'
// 這個方式能夠在任何組件裏直接用 this.$EventBus 調用
Vue.prototype.$EventBus = EventBus
// 也能夠直接這樣使用,不須要第一步的建立
// import Vue from 'vue'
// Vue.prototype.$EventBus = new Vue()
複製代碼
注意: 兩種方法任選其一,本是採用第二種方法
要使用監聽方法,只要調用EventBus下的$on方法
具體使用以下:
建立 ./a.vue
<template>
<div>
<h3>頁面A</h3>
<router-link to="/b">
跳轉B頁面
</router-link>
</div>
</template>
<script>
export default {
created () {
console.log('----A頁面監聽事件----')
// 使用Vue原型鏈引入
this.$EventBus.$on('getNum', (num) => {
console.log('num', num)
})
}
}
</script>
複製代碼
而接下就是使用遞交方法,
一樣的,只要調用EventBus下的$emit方法
具體使用以下:
建立 ./b.vue
<template>
<div>
<h3>B頁面</h3>
<router-link to="/a">
跳轉A頁面
</router-link>
</div>
</template>
<script>
export default {
created () {
console.log('----B頁面遞交事件----')
const num = 2
// 使用Vue原型鏈引入
this.$EventBus.$emit('getNum', num)
}
}
</script>
複製代碼
讀者必定要特別注意!!!
像這樣設置路由!
// src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import a from '../views/a'
import b from '../views/b'
Vue.use(VueRouter)
const routes = [
{
path: '/a',
name: 'a',
component: a
},
{
path: '/b',
name: 'b',
component: b
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
複製代碼
而以後點兩個路由跳轉
就有如下的效果
細心的讀者會發現: 上面輸出 num 2 會每次遞增 1 次 輸出
這是由於沒有對監聽事件銷燬,從致使了內存泄露
應該在調用 方法()頁面的生命週期中添加off
// a.vue 添加$off方法,防止內存泄露
beforeDestroy () {
console.log('----A頁面銷燬監聽事件----')
this.$EventBus.$off('getNum')
}
複製代碼
這樣就是完美的使用方式了
讀者應該還要注意的是!!! 事件順序:綁定監聽事件->遞交事件->獲取值->銷燬監聽事件
本文的完整代碼以下:
<template>
<div>
<h3>頁面A</h3>
<router-link to="/b">
跳轉B頁面
</router-link>
</div>
</template>
<script>
export default {
created () {
console.log('----A頁面監聽事件----')
// 使用Vue原型鏈引入
this.$EventBus.$on('getNum', (num) => {
console.log('num', num)
})
},
beforeDestroy () {
console.log('----A頁面銷燬監聽事件----')
// 使用Vue原型鏈引入
this.$EventBus.$off('getNum')
}
}
</script>
複製代碼
<template>
<div>
<h3>B頁面</h3>
<router-link to="/a">
跳轉A頁面
</router-link>
</div>
</template>
<script>
export default {
created () {
console.log('----B頁面遞交事件----')
const num = 2
// 使用Vue原型鏈引入
this.$EventBus.$emit('getNum', num)
}
}
</script>
複製代碼
總結一下事件流程就是
建立eventBus->引入同一個實例->綁定(訂閱)監聽事件->遞交(發佈)事件->銷燬監聽事件
感謝閱讀