📄 前端数据状态管理 _ PIGCLOUD

](https://www.pig4cloud.com/)
产品
商业版
生态🔥
📄 前端数据状态管理
pigcloud
开始之前
框架中数据状态使用 vuex Module 模块化进行管理,您可能需要了解 vuex 核心概念 Module (opens new window)
# pinia
代码位置:/src/stores
相关文档:pinia 官网 (opens new window)
相关文档:vuex 3.x 官网 (opens new window)
# 全局引入
页面模块已做全局自动引入,代码位置:/@/store/index.ts。import.meta.globEager (opens new window)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const modulesFiles = import.meta.globEager("./modules/*.ts"); const pathList: string[] = [];
for (const path in modulesFiles) { pathList.push(path); }
const modules = pathList.reduce( (modules: { [x: string]: any }, modulePath: string) => { const moduleName = modulePath.replace(/^\.\/modules\/(.*)\.\w+$/, "$1"); const value = modulesFiles[modulePath]; modules[moduleName] = value.default; return modules; }, {} );
Copied!
|
# 定义接口
# 1. interface 定义
/@/store/interface/index.ts,如:路由缓存列表 KeepAliveNamesState
1 2 3 4 5 6 7 8 9
| export interface KeepAliveNamesState { keepAliveNames: Array<string>; }
Copied!
|
# 2. interface 使用
在 /@/store/modules/ 新增 keepAliveNames.ts,界面写入如下代码:注意需要开启 namespaced: true 文件名称即模块名称。(vuex Module 命名空间 (opens new window))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import { Module } from "vuex";
import { KeepAliveNamesState, RootStateTypes } from "/@/store/interface/index";
const keepAliveNamesModule: Module<KeepAliveNamesState, RootStateTypes> = { namespaced: true, state: { keepAliveNames: [], }, mutations: { getCacheKeepAlive(state: any, data: Array<string>) { state.keepAliveNames = data; }, }, actions: { async setCacheKeepAlive({ commit }, data: Array<string>) { commit("getCacheKeepAlive", data); }, }, };
export default keepAliveNamesModule;
Copied!
|
# 定义模块
如上所示,我们在 /@/store/modules/ 下新增了 keepAliveNames.ts 文件,并定义了方法 mutations、actions
# 使用模块
# 1. 在 .ts 中使用
1 2 3 4 5 6 7 8 9 10 11 12
| import { store } from "/@/store/index.ts";
store.dispatch("keepAliveNames/setCacheKeepAlive", cacheList);
Copied!
|
# 2. 在 .vue 中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <template> <div v-if="getThemeConfig.isLockScreen">在 .vue 中使用</div> </template>
<script lang="ts"> import { computed, defineComponent } from "vue"; import { useStore } from "/@/store/index"; export default defineComponent({ name: "app", setup() { const store = useStore(); const getThemeConfig = computed(() => { return store.state.themeConfig.themeConfig; }); }, }); </script>
Copied!
|
📄 前端权限管理 📄 前端组件路由管理
