Pinia 状态管理
代码: /src/stores
全局引入
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;
},
{}
);
定义接口
Interface 定义
在 /@/store/interface/index.ts
中定义接口,例如路由缓存列表 KeepAliveNamesState
:
// 路由缓存列表
export interface KeepAliveNamesState {
keepAliveNames: Array<string>;
}
Interface 使用
在 /@/store/modules/
目录下创建 keepAliveNames.ts
,写入如下代码:
import { Module } from "vuex";
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;
定义模块
如上所示,我们在 /@/store/modules/
下新增了 keepAliveNames.ts
文件,并定义了方法 mutations
、actions
。
使用模块
在 TypeScript 文件中使用
import { store } from "/@/store/index.ts";
// dispatch
store.dispatch("keepAliveNames/setCacheKeepAlive", cacheList);
// 或者 commit
// store.commit("keepAliveNames/getCacheKeepAlive", cacheList);
在 Vue 组件中使用
<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>
♥️ 获取支持
遇到问题?
如果您在使用过程中遇到任何问题、有功能建议或需求,请点击此卡片前往 Gitee 仓库提交 Issue。