当我们做一些小项目,没必要用到vuex的时候,但是又要用类似vuex的功能,这个时候就可以用eventBus或者observable
先说一下eventBus
声明一个全局Vue实例变量 eventBus , 把所有的通信数据,事件监听都存储到这个变量上
在main.js中
Vue.prototype.$eventBus =new Vue()
然后在父组件里面开始传值
methods:{
click(){
this.$eventBus.$emit('eventBus','你要干啥')
}
}
子组件接收
mounted:{
this.$eventBus.$on('eventBus',v=>{
console.log('eventBus',v)
})
}
再来看一下observable
Vue 内部会用它来处理 data 函数返回的对象; 返回的对象可以直接用于渲染函数和计算属性内,并且会在发生改变时触发相应的更新
新建立一个js文件
import Vue from 'vue'
export const store = Vue.observable({count:0})
export const mutations = {
setCount(count){
store.count = count
}
}
然后在组件中引入这个文件
import {store,mutations}
<button @click="setCount(count+1)">+</button>
<span>{{count}}</span>
<button @click="setCount(count-1)">-</button>
computed: {
count(){
return store.count
}
},
methods:{
setCount:mutations.setCount,
}