當我們做一些小項目,沒必要用到vuex的時候,但是又要用類似vuex的功能,這個時候就可以用eventBus或者observable
eventBus
聲明一個全局Vue實例變量 eventBus , 把所有的通信數(shù)據(jù),事件監(jiān)聽都存儲到這個變量上
- main.js
Vue.prototype.$eventBus = new Vue()
- parent.vue
methods: {
click() {
this.$eventBus.$emit('eventBus', '哈哈哈')
}
}
- children.vue
mounted:{
this.$eventBus.$on('eventBus', this.getData)
}
有時候我們遇到的頁簽組件的時候,多次點擊頁簽會頻繁的觸發(fā) eventBus 事件,這時候子組件接收事件的時候,需要先取消事件:
mounted:{
this.$eventBus.$off('eventBus', this.getData)
}
注: vue3 移除了 eventBus , 推薦使用
mitt
observable
Vue 內(nèi)部會用它來處理 data 函數(shù)返回的對象; 返回的對象可以直接用于渲染函數(shù)和計算屬性內(nèi),并且會在發(fā)生改變時觸發(fā)相應的更新
- 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>