gpt4 book ai didi

javascript - 使用 Vuex 的全局事件总线 - 始终通知订阅者

转载 作者:可可西里 更新时间:2023-11-01 02:27:36 27 4
gpt4 key购买 nike

我在 Vue 中使用全局事件总线已经有一段时间了——类似于 const bus = new Vue() .工作正常,但是,订阅的处理可能会变得非常冗长。

假设我在一个组件中订阅了一个事件:

mounted() {
bus.$on('some.event', callback)
}

我必须跟踪回调并在 beforeDestroy 中正确处理它.这可以使用全局混合来稍微简化,但因为我使用的是 <keep-alive> , 我必须区分 mounted 中的订阅和 activated回调。

所以我想我应该给 Vuex 一个机会来管理它,因为 watchers 是由框架处理的。我提出了以下建议。

只要发布了对象或数组,似乎就可以正常工作。原始数据似乎不会触发 react ,尽管被包裹在外部对象中,即 { data: 123 }

我正在寻找有关通知订阅者的替代解决方案。到目前为止,我所看到的只是内部 notify方法,使用起来感觉不太安全。

eventstore.js

import Vue from 'vue'

const state = {
events: {}
}

const actions = {
publish({commit}, payload) {
commit('publish_event', payload)
}
}

const mutations = {
publish_event(state, payload) {
if(!state.events[payload.key]) {
Vue.set(state.events, payload.key, { data: payload.data })
} else {
state.events[payload.key] = { data: payload.data }
}
}
}

const getters = {
events: state => state.events
}

export default {
state,
actions,
mutations,
getters
}

globalmixin.js

methods: {
publish(key, data) {
this.$store.dispatch('publish', { key, data })
}
}

somecomponent.vue

function mapEventGetters(eventKeys) {
return _.reduce(eventKeys, (result, current) => {
result[current] = function() {
return _.get(this, `$store.getters.events.${current}.data`)
}
return result
}, {})
}
computed: {
...mapEventGetters(['foo_bar'])
},
watch: {
'foo_bar'(value) {
console.log(`foo_bar changed to ${value}`)
}
}

最佳答案

这个API会打破Vuex的核心概念——Vuex的数据流。客户端将能够在 Vuex 中的任何地方改变/读取存储状态。

老实说,这种方式不需要在 Vuex 中实现,因为它只是一个事件发射器。我建议您在操作中使用一些事件发射器(可能是空的 Vue 实例)。

export const emitter = new Vue()

export default {
// ...

actions: {
// should be called when the store is initialized
// to observe events
observe({ dispatch, commit }) {
emitter.$on('some-event', () => {
commit('someEvent')
})

emitter.$on('other-event', () => {
dispatch('otherEvent')
})
},

// notify some event in action
notify({ state }) {
emitter.$emit('notify', state.someValue)
}
}
}

在github上搜索一次就解决了我的问题。垫是帮助你。谢谢!!

关于javascript - 使用 Vuex 的全局事件总线 - 始终通知订阅者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53597963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com