全栈笔记

Vue 两个简易代替 vuex 的方法

2022-12-06  本文已影响0人  小贤笔记

当我们做一些小项目,没必要用到vuex的时候,但是又要用类似vuex的功能,这个时候就可以用eventBus或者observable

eventBus

声明一个全局Vue实例变量 eventBus , 把所有的通信数据,事件监听都存储到这个变量上

Vue.prototype.$eventBus = new Vue()
methods: {
  click() {
    this.$eventBus.$emit('eventBus', '哈哈哈')
  }
}
mounted:{
  this.$eventBus.$on('eventBus', this.getData)
}

有时候我们遇到的页签组件的时候,多次点击页签会频繁的触发 eventBus 事件,这时候子组件接收事件的时候,需要先取消事件:

mounted:{
  this.$eventBus.$off('eventBus', this.getData)
}

注: vue3 移除了 eventBus , 推荐使用 mitt

observable

Vue 内部会用它来处理 data 函数返回的对象; 返回的对象可以直接用于渲染函数和计算属性内,并且会在发生改变时触发相应的更新

import Vue from 'vue'

export const store = Vue.observable({ count: 0 })
export const mutations = {
  setCount(count) {
    store.count = count
  }
}
<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>
上一篇 下一篇

猜你喜欢

热点阅读