當(dāng)我們做一些小項(xiàng)目沟突,沒(méi)必要用到vuex的時(shí)候,但是又要用類似vuex的功能捕传,這個(gè)時(shí)候就可以用eventBus或者observable
eventBus
聲明一個(gè)全局Vue實(shí)例變量 eventBus , 把所有的通信數(shù)據(jù)惠拭,事件監(jiān)聽都存儲(chǔ)到這個(gè)變量上
- main.js
Vue.prototype.$eventBus = new Vue()
- parent.vue
methods: {
click() {
this.$eventBus.$emit('eventBus', '哈哈哈')
}
}
- children.vue
mounted:{
this.$eventBus.$on('eventBus', this.getData)
}
有時(shí)候我們遇到的頁(yè)簽組件的時(shí)候,多次點(diǎn)擊頁(yè)簽會(huì)頻繁的觸發(fā) eventBus 事件,這時(shí)候子組件接收事件的時(shí)候职辅,需要先取消事件:
mounted:{
this.$eventBus.$off('eventBus', this.getData)
}
注: vue3 移除了 eventBus , 推薦使用
mitt
observable
Vue 內(nèi)部會(huì)用它來(lái)處理 data 函數(shù)返回的對(duì)象; 返回的對(duì)象可以直接用于渲染函數(shù)和計(jì)算屬性內(nèi)棒呛,并且會(huì)在發(fā)生改變時(shí)觸發(fā)相應(yīng)的更新
- store.js
import Vue from 'vue'
export const store = Vue.observable({ count: 0 })
export const mutations = {
setCount(count) {
store.count = count
}
}
- test.vue
<template>
<div>
<span>{{ count }}</span>
<button @click="setCount">按鈕</button>
</div>
</template>
<script>
import { store, mutations } from 'xxx/store.js'
computed: {
count() {
return store.count
}
},
methods: {
setCount() {
mutations.setCount(this.count + 1)
}
}
</script>