本文记录了如何使用vuex建立响应式全局变量,内容有:按类别建立多模块、如何引入、使用、如何不借助第三方工具在localStorage、sessionStorage中实现数据持久化,以及vuex store state的赋值问题。
项目路径下,终端内执行
vue add vuex -S
或者
yarn install vuex -S
可以在此文件内直接编辑全局根参数,或引入模块级参数
import {createStore} from 'vuex'
export default createStore({
state: {
},
getters: {},
mutations: {},
actions: {},
modules: { )
在store/modeules目录下新建模块级参数文件。例如
/**
* app全局变量
*@author MuYi
*@date 2022/3/21 8:58
*@version 1.0
*/
export default {
namespace: 'true',
state() {
return {
/**
* app信息
*/
appInfo: {
registerCompany: '请联系注册您的公司',
version: '1.0.0',
copyright: 'WinTown Software studio All rights reserved.',
copyrightYear: '©2021-2022',
author: ''
},
theme: {
menuMode: 'vertical',
colorBackground: '#009999',
}
}
},
mutations: {
/**
* 设置app信息
* @param appInfo
*/
saveAppInfo(state, appInfo) {
state.appInfo = appInfo;
},
saveTheme(state, theme) {
state.theme = theme;
}
},
actions: {
updateTheme(context, theme) {
context.commit("theme", theme);
},
updateAppInfo(context, appInfo) {
context.commit("appInfo", appInfo)
}
},
getters: {
theme(state) {
return state.theme;
},
appInfo(state) {
return state.appInfo;
}
}
}
import {createStore} from 'vuex'
import appGlobal from "@/store/modules/appGlobal";
export default createStore({
state: {
},
getters: {},
mutations: {},
actions: {},
modules: {
/**
* app全局参数
*/
appGlobal,
}
})
main.js文件中
import store from './store'
程序片段
{{appInfo.registerCompany}}
... ...