美文网首页全栈笔记
Vue 两个简易代替 vuex 的方法

Vue 两个简易代替 vuex 的方法

作者: 小贤笔记 | 来源:发表于2022-12-06 21:15 被阅读0次

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

eventBus

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

  • main.js
Vue.prototype.$eventBus = new Vue()
  • parent.vue
methods: {
  click() {
    this.$eventBus.$emit('eventBus', '哈哈哈')
  }
}
  • children.vue
mounted:{
  this.$eventBus.$on('eventBus', this.getData)
}

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

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

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

observable

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

  • 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>

相关文章

网友评论

    本文标题:Vue 两个简易代替 vuex 的方法

    本文链接:https://www.haomeiwen.com/subject/vflvfdtx.html