Vue两个简易代替vuex的方法(eventBus,observable)

时间:2021-07-12
本文章向大家介绍Vue两个简易代替vuex的方法(eventBus,observable),主要包括Vue两个简易代替vuex的方法(eventBus,observable)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

当我们做一些小项目,没必要用到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,
}

 

原文地址:https://www.cnblogs.com/smile-fanyin/p/15002992.html