前端数据状态管理

前端数据状态管理

PIGCLOUD

📄 前端数据状态管理 _ 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.tsimport.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";
// 此处加上 `.ts` 后缀报错,具体原因不详
import { KeepAliveNamesState, RootStateTypes } from "/@/store/interface/index";

const keepAliveNamesModule: Module<KeepAliveNamesState, RootStateTypes> = {
namespaced: true,
state: {
keepAliveNames: [],
},
mutations: {
// 设置路由缓存(name字段)
getCacheKeepAlive(state: any, data: Array<string>) {
state.keepAliveNames = data;
},
},
actions: {
// 设置路由缓存(name字段)
async setCacheKeepAlive({ commit }, data: Array<string>) {
commit("getCacheKeepAlive", data);
},
},
};

export default keepAliveNamesModule;




Copied!

# 定义模块

如上所示,我们在 /@/store/modules/ 下新增了 keepAliveNames.ts 文件,并定义了方法 mutationsactions

# 使用模块

# 1. 在 .ts 中使用

1
2
3
4
5
6
7
8
9
10
11
12
import { store } from "/@/store/index.ts";

// dispatch
store.dispatch("keepAliveNames/setCacheKeepAlive", cacheList);

// 或者 commit
// store.commit("keepAliveNames/getCacheKeepAlive", 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!

📄 前端权限管理 📄 前端组件路由管理

  • 标题: 前端数据状态管理
  • 作者: PIGCLOUD
  • 创建于 : 2024-01-01 00:00:00
  • 更新于 : 2025-09-22 14:27:28
  • 链接: https://anime-blog.52lin.site/📄 前端数据状态管理 _ PIGCLOUD/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。