定义vuex (this指向Store实例,可以通过 this._vm 访问Vue实例)
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate';
import user from './modules/user'
import dataManagerService from './modules/dataManagerService'
Vue.use(Vuex)
const store = new Vuex.Store({
plugins: [createPersistedState({
paths: ["user", "dataManagerService.activeBillMacButton", "token"]
})],
modules: {
user,
theme,
dataManagerService
},
state: {
token: "",
dictMap: new Map()
},
mutations: {
setToken (state, token) {
state.token = token
},
setDictMap (state, dictMap) {
state.dictMap = dictMap
}
},
actions: {
async loginAndInitAsync ({ commit, state }, payloads) {
const loginRes = await this._vm.$SendRequest(payloads);
const token = loginRes?.access_token;
commit('setToken', token)
const dictsRes = await this._vm.$SendRequest({
url: "/cloud/sys/common/dict/map",
});
const dictMap = new Map();
Object.entries(dictsRes).forEach(([type, dicts]) => {
let dictList = [];
for (const key in dicts) {
dictList.push({ name: dicts[key], value: key })
}
dictMap.set(type, dictList)
})
commit('setDictMap', dictMap)
console.log('dictMap', dictMap);
}
},
getters: {
getDictsByType: (state, getters) => (type, needOptionOfAll = false) => {
const dictMap = state.dictMap.get(type);
if (needOptionOfAll) {
dictMap.unshift({ name: "全部", value: null })
}
return state.dictMap.get(type)
}
}
})
组件中使用vuex(获取根目录下的不带模块路径即可),以下演示了通过辅助函数和直接操作两大类
import { mapState, mapGetters, mapMutations, mapActions} from 'vuex'
computed: {
...mapState(['token']),
...mapState({
a: state => state.some.nested.module.a,
b: state => state.some.nested.module.b
}),
...mapState('some/nested/module', [
'stateName'
]),
...mapGetters('moduleName', [
'getterName',
]),
},
methods: {
methods: {
...mapActions([
'moduleName/actionName',
]),
...mapActions('moduleName', [
'actionName',
]),
...mapMutations('moduleName', [
'mutationName',
]),
test () {
const token = this.$store.state.token;
this.$store.commit('setToken', "123456")
this.$store.state['moduleName/stateName']
this.$store.getters['moduleName/getterName']
this.$store.dispatch('moduleName/actionName')
this.$store.commit('moduleName/mutationName')
}
}
},
modules
const moduleA = {
namespaced: true,
state:{},
mutations: { ... },
actions: { ... },
getters: { ... }
}
注意点 需遵守 Vue 的响应规则
- 最好提前在你的 store 中初始化好所有所需属性。
- 当需要在对象上添加新属性时,你应该
- 使用
Vue.set(obj, 'newProp', 123),
- 以新对象替换老对象。