多实例
允许创建多实例,各store实例彼此互相独立,状态互不干扰,不需要考虑命名空间的问题,而且可以随时动态创建一个新的store,更灵活且移植性更高。相对较于modules,更推荐多实例模式
联合多个store实例
如果需要使用外部store的数据,mpx
也提供的createStore支持传入deps
参数,表示注入的外部store。在store内部访问外部store的资源使用如下方式(都是加namespace形式的path访问
模式)。由于注入store的各部分(state, getters, mutations, actions)是 以key作为namespace merge在options对应属性内部的,所以deps的key要防止冲突
基础例子
例子:
import {createStore} from '@mpxjs/core'
const store1 = createStore({
state: {
a: 1
},
getters: {
getA(state) {
return state.a
}
},
mutations: {
setA(state, payload) {
state.a = payload
}
},
actions: {
actionA({commit}, payload) {
commit('setA', payload)
}
}
})
const store2 = createStore({
state: {
b: 1
},
getters: {
getB(state, getters) {
// 访问外部store1的数据,按路径访问
return state.b + state.store1.a + getters.store1.getA
}
},
mutations: {
setB(state, payload) {
state.b = payload
}
},
actions: {
actionB({dispatch, commit}, payload) {
// 同理,mutations、actions访问外部store1的方法时,也是按路径访问
commit('store1.setA', payload)
dispatch('store1.actionA', payload)
commit('setB', payload)
}
},
deps: {
store1
}
})
export {store1, store2}
多store注入下的’store.mapGetters、store.mapMuations、store.mapActions’
import {createStore, createComponent} from '@mpxjs/core'
const store1 = createStore({
state: {
a: 1
},
getters: {
getA(state, getters) {
return state.b + state.store1.a + getters.store1.getA
}
},
mutations: {
setA(state, payload) {
state.a = payload
}
},
actions: {
actionA({commit}, payload) {
commit('setA', payload)
}
}
})
const store2 = createStore({
state: {
b: 1
},
getters: {
getB(state) {
return state.b + state.store1.a
}
},
mutations: {
setB(state, payload) {
state.b = payload
}
},
actions: {
actionB({dispatch, commit}, payload) {
commit('store1.setA', payload)
dispatch('store1.actionA', payload)
commit('setB', payload)
}
},
deps: {
// xx: store1
store1
}
})
// 组件内部使用store
createComponent({
computed: {
...store2.mapGetters(['getB']),
// 对于依赖store1的引入,可以使用以下两种方式,类似的mapMutations、mapActions, mapState
...store2.mapgetters({
getA: 'store1.getA'
}),
...store2.mapGetters('store1', ['getA'])
}
})