分模块维护
import Vuex from 'vuex'
import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './actions/actions'
const isDev = process.env.NODE_ENV === 'development'
export default () => {
const store = new Vuex.Store({
strict: isDev,
state: defaultState,
mutations,
getters,
actions
// plugins: [ //插件声明处
// (store) => {
//store.subscribe
// console.log('my plugin invoked')
// }
// ]
modules: { //模块划分
a: {
namespaced: true, //加入为true后, 命名空间,
state: {
text: 1
},
mutations: {
updateText (state, text) { //单独的a模块的state,注意:默认mutation是全局相通的
console.log('a.state', state)
state.text = text
}
},
getters: {
textPlus (state, getters, rootState) { //第三个参数是全局参数
return state.text + rootState.b.text
}
},
actions: {
add ({ state, commit, rootState }) {
commit('updateCount', { num: 56789 }, { root: true })//全局修改的话,第三个参数root:true
}
}
},
b: {
namespaced: true,
state: {
text: 2
},
actions: {
testAction ({ commit }) {
commit('a/updateText', 'test text', { root: true })
//全局修改的话,第三个参数root:true,第一个参数加入限制:a/updateText
}
}
}
}
})复制代码
模块用法:app.vue
mounted(){
this['b/testAction']() //如有namespace
}
computed:{
textA(){
return this.$store.state.b.text //调用b模块下的text
}
...mapState({
testA:state =>state.a.text,
textC:state =>state.c.text //动态注册模块
})
...mapGetters({
'fullName':'fullName',
textPlus:'a/textPlus'
})
},
methods:{
...mapActions(['updateCourtAsync','a/add','testAction'])
}复制代码
动态注册模块
store.registerModule('c',{
state:{
text:3
}
})
复制代码
解绑模块
store.unregisterModule('c')
复制代码
store API
store.watch((state)=>state.count+1,(newCount)=>{
// 第一个参数发生变化,出发第二个参数方法
})
复制代码
这两个常用在插件定义,声明在store处
订阅:每次mutation的调用和他的参数
store.subscribe((mutation,state)=>{
console.log(mutation.type)
console.log(mutation.payload) //调的这个mutation和他的值
})复制代码
订阅:每次action的调用和他的参数
store.subscribeAction((action,state)=>{
console.log(action.type)
console.log(action.payload) //调的这个action和他的值
})复制代码