Browse Source

workflow: use pinia replace vuex and fix some bug

xiaoxian521 3 years ago
parent
commit
d9132ffa64

+ 2 - 2
mock/asyncRoutes.ts

@@ -21,7 +21,7 @@ const systemRouter = {
       // component: () => import("/@/views/system/user/index.vue"),
       meta: {
         title: "message.hsBaseinfo",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -31,7 +31,7 @@ const systemRouter = {
       // component: () => import("/@/views/system/dict/index.vue"),
       meta: {
         title: "message.hsDict",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },

+ 17 - 20
package-lock.json

@@ -25,6 +25,7 @@
         "nprogress": "^0.2.0",
         "path": "^0.12.7",
         "path-to-regexp": "^6.2.0",
+        "pinia": "^2.0.0-alpha.19",
         "resize-observer-polyfill": "^1.5.1",
         "v-contextmenu": "^3.0.0",
         "vue": "^3.0.11",
@@ -33,7 +34,6 @@
         "vue-router": "^4.0.8",
         "vue-types": "^3.0.2",
         "vuedraggable": "^4.0.1",
-        "vuex": "^4.0.1",
         "vxe-table": "^4.0.18-beta.0",
         "wangeditor": "^4.0.3",
         "xe-ajax": "^4.0.5",
@@ -2088,6 +2088,14 @@
         "node": ">=0.10.0"
       }
     },
+    "node_modules/pinia": {
+      "version": "2.0.0-alpha.19",
+      "resolved": "https://registry.npmjs.org/pinia/-/pinia-2.0.0-alpha.19.tgz",
+      "integrity": "sha512-U/FvKm2tVUdqEuPorkYvD3oCgIj/u5EnF9TbX5dEpkNkoWKQM1i23e97QKtQFGuTxMSfzmBFFINv4A9VeVZ1wQ==",
+      "dependencies": {
+        "@vue/devtools-api": "^6.0.0-beta.10"
+      }
+    },
     "node_modules/postcss": {
       "version": "8.2.10",
       "resolved": "https://registry.npm.taobao.org/postcss/download/postcss-8.2.10.tgz",
@@ -2760,17 +2768,6 @@
         "sortablejs": "1.10.2"
       }
     },
-    "node_modules/vuex": {
-      "version": "4.0.1",
-      "resolved": "https://registry.npmjs.org/vuex/-/vuex-4.0.1.tgz",
-      "integrity": "sha512-MddakQTAnImDkK1YhEESowKSU5KcjqHH3L1ScPx1lj6NzDDX0FuRBZqJoME5O7/nvj9puudDf6xnWU2w/cqI7g==",
-      "dependencies": {
-        "@vue/devtools-api": "^6.0.0-beta.11"
-      },
-      "peerDependencies": {
-        "vue": "^3.0.2"
-      }
-    },
     "node_modules/vxe-table": {
       "version": "4.0.18-beta.0",
       "resolved": "https://registry.npmjs.org/vxe-table/-/vxe-table-4.0.18-beta.0.tgz",
@@ -4590,6 +4587,14 @@
       "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=",
       "dev": true
     },
+    "pinia": {
+      "version": "2.0.0-alpha.19",
+      "resolved": "https://registry.npmjs.org/pinia/-/pinia-2.0.0-alpha.19.tgz",
+      "integrity": "sha512-U/FvKm2tVUdqEuPorkYvD3oCgIj/u5EnF9TbX5dEpkNkoWKQM1i23e97QKtQFGuTxMSfzmBFFINv4A9VeVZ1wQ==",
+      "requires": {
+        "@vue/devtools-api": "^6.0.0-beta.10"
+      }
+    },
     "postcss": {
       "version": "8.2.10",
       "resolved": "https://registry.npm.taobao.org/postcss/download/postcss-8.2.10.tgz",
@@ -5126,14 +5131,6 @@
         "sortablejs": "1.10.2"
       }
     },
-    "vuex": {
-      "version": "4.0.1",
-      "resolved": "https://registry.npmjs.org/vuex/-/vuex-4.0.1.tgz",
-      "integrity": "sha512-MddakQTAnImDkK1YhEESowKSU5KcjqHH3L1ScPx1lj6NzDDX0FuRBZqJoME5O7/nvj9puudDf6xnWU2w/cqI7g==",
-      "requires": {
-        "@vue/devtools-api": "^6.0.0-beta.11"
-      }
-    },
     "vxe-table": {
       "version": "4.0.18-beta.0",
       "resolved": "https://registry.npmjs.org/vxe-table/-/vxe-table-4.0.18-beta.0.tgz",

+ 1 - 1
package.json

@@ -28,6 +28,7 @@
     "nprogress": "^0.2.0",
     "path": "^0.12.7",
     "path-to-regexp": "^6.2.0",
+    "pinia": "^2.0.0-alpha.19",
     "resize-observer-polyfill": "^1.5.1",
     "v-contextmenu": "^3.0.0",
     "vue": "^3.0.11",
@@ -36,7 +37,6 @@
     "vue-router": "^4.0.8",
     "vue-types": "^3.0.2",
     "vuedraggable": "^4.0.1",
-    "vuex": "^4.0.1",
     "vxe-table": "^4.0.18-beta.0",
     "wangeditor": "^4.0.3",
     "xe-ajax": "^4.0.5",

+ 4 - 4
src/components/HamBurger/src/HamBurger.vue

@@ -16,7 +16,7 @@
 </template>
 
 <script>
-import { defineComponent } from "vue";
+import { defineComponent } from "vue"
 export default defineComponent({
   name: "HamBurger",
   props: {
@@ -28,10 +28,10 @@ export default defineComponent({
   emits: ["toggleClick"],
   setup(props, ctx) {
     const toggleClick = () => {
-      ctx.emit("toggleClick");
-    };
+      ctx.emit("toggleClick")
+    }
 
-    return { toggleClick };
+    return { toggleClick }
   },
 });
 </script>

+ 10 - 9
src/layout/components/Navbar.vue

@@ -1,7 +1,7 @@
 <template>
   <div class="navbar">
     <Hamburger
-      :is-active="sidebar.opened"
+      :is-active="pureApp.sidebar.opened"
       class="hamburger-container"
       @toggleClick="toggleSideBar"
     />
@@ -45,9 +45,9 @@ import { ref, defineComponent, onMounted, unref, watch } from "vue";
 import Breadcrumb from "/@/components/BreadCrumb";
 import Hamburger from "/@/components/HamBurger";
 import screenfull from "../components/screenfull/index.vue";
-import { useMapGetters } from "../store";
 import { useRouter, useRoute } from "vue-router";
-import { useStore } from "vuex";
+import { useAppStoreHook } from "/@/store/modules/app";
+import { mapGetters } from "pinia";
 import { storageSession } from "/@/utils/storage";
 import ch from "/@/assets/ch.png";
 import en from "/@/assets/en.png";
@@ -70,7 +70,7 @@ export default defineComponent({
   setup() {
     let langs = ref(true);
 
-    const store = useStore();
+    const pureApp = useAppStoreHook();
     const router = useRouter();
     const route = useRoute();
 
@@ -108,6 +108,10 @@ export default defineComponent({
       emitter.emit("openPanel");
     }
 
+    function toggleSideBar() {
+      pureApp.toggleSideBar();
+    }
+
     onMounted(() => {
       document
         .querySelector(".el-dropdown__popper")
@@ -118,11 +122,8 @@ export default defineComponent({
     });
 
     return {
-      // @ts-ignore
-      ...useMapGetters(["sidebar"]),
-      toggleSideBar() {
-        store.dispatch("app/toggleSideBar");
-      },
+      pureApp,
+      toggleSideBar,
       langs,
       usename,
       toggleLang,

+ 9 - 6
src/layout/components/sidebar/index.vue

@@ -11,7 +11,7 @@
         @select="menuSelect"
       >
         <sidebar-item
-          v-for="route in routes"
+          v-for="route in routeStore.wholeRoutes"
           :key="route.path"
           :item="route"
           :base-path="route.path"
@@ -31,21 +31,24 @@ import {
   onBeforeMount
 } from "vue";
 import { useRoute, useRouter } from "vue-router";
-import { useStore } from "vuex";
+import { useAppStoreHook } from "/@/store/modules/app";
 import SidebarItem from "./SidebarItem.vue";
 import { algorithm } from "../../../utils/algorithm";
 import { useDynamicRoutesHook } from "../tag/tagsHook";
 import { emitter } from "/@/utils/mitt";
 import Logo from "./Logo.vue";
 import { storageLocal } from "/@/utils/storage";
+import { usePermissionStoreHook } from "/@/store/modules/permission";
 
 export default defineComponent({
   name: "sidebar",
   components: { SidebarItem, Logo },
   setup() {
+    const routeStore = usePermissionStoreHook();
+
     const router = useRouter().options.routes;
 
-    const store = useStore();
+    const pureApp = useAppStoreHook();
 
     const route = useRoute();
 
@@ -89,11 +92,11 @@ export default defineComponent({
     });
 
     return {
-      routes: computed(() => algorithm.increaseIndexes(router)),
       activeMenu,
-      isCollapse: computed(() => !store.getters.sidebar.opened),
+      isCollapse: computed(() => !pureApp.getSidebarStatus),
       menuSelect,
-      showLogo
+      showLogo,
+      routeStore
     };
   }
 });

+ 17 - 16
src/layout/index.vue

@@ -3,7 +3,7 @@
     <div
       v-if="device === 'mobile' && sidebar.opened"
       class="drawer-bg"
-      @click="handleClickOutside"
+      @click="handleClickOutside(false)"
     />
     <!-- 侧边栏 -->
     <sidebar class="sidebar-container" v-if="!containerHiddenSideBar" />
@@ -42,7 +42,8 @@ import {
   onBeforeMount,
   onBeforeUnmount
 } from "vue";
-import { useStore } from "vuex";
+import { useAppStoreHook } from "/@/store/modules/app";
+import { useSettingStoreHook } from "/@/store/modules/settings";
 import { useEventListener, useFullscreen } from "@vueuse/core";
 import { toggleClass, removeClass } from "/@/utils/operate";
 let hiddenMainContainer = "hidden-main-container";
@@ -67,7 +68,8 @@ export default {
     tag
   },
   setup() {
-    const store = useStore();
+    const pureApp = useAppStoreHook();
+    const pureSetting = useSettingStoreHook();
 
     const router = useRouter();
     const route = useRoute();
@@ -78,15 +80,15 @@ export default {
 
     const set: setInter = reactive({
       sidebar: computed(() => {
-        return store.state.app.sidebar;
+        return pureApp.sidebar;
       }),
 
       device: computed(() => {
-        return store.state.app.device;
+        return pureApp.device;
       }),
 
       fixedHeader: computed(() => {
-        return store.state.settings.fixedHeader;
+        return pureSetting.fixedHeader;
       }),
 
       classes: computed(() => {
@@ -99,16 +101,16 @@ export default {
       })
     });
 
+    const handleClickOutside = (params: Boolean) => {
+      pureApp.closeSideBar({ withoutAnimation: params });
+    };
+
     watchEffect(() => {
       if (set.device === "mobile" && !set.sidebar.opened) {
-        store.dispatch("app/closeSideBar", { withoutAnimation: false });
+        handleClickOutside(false);
       }
     });
 
-    const handleClickOutside = () => {
-      store.dispatch("app/closeSideBar", { withoutAnimation: false });
-    };
-
     const $_isMobile = () => {
       const rect = document.body.getBoundingClientRect();
       return rect.width - 1 < WIDTH.value;
@@ -117,10 +119,9 @@ export default {
     const $_resizeHandler = () => {
       if (!document.hidden) {
         const isMobile = $_isMobile();
-        store.dispatch("app/toggleDevice", isMobile ? "mobile" : "desktop");
-
+        pureApp.toggleDevice(isMobile ? "mobile" : "desktop");
         if (isMobile) {
-          store.dispatch("app/closeSideBar", { withoutAnimation: true });
+          handleClickOutside(true);
         }
       }
     };
@@ -146,8 +147,8 @@ export default {
     onMounted(() => {
       const isMobile = $_isMobile();
       if (isMobile) {
-        store.dispatch("app/toggleDevice", "mobile");
-        store.dispatch("app/closeSideBar", { withoutAnimation: true });
+        pureApp.toggleDevice("mobile");
+        handleClickOutside(true);
       }
       toggleClass(
         unref(containerHiddenSideBar),

+ 0 - 14
src/layout/store.ts

@@ -1,14 +0,0 @@
-import { computed, ComputedRef } from "vue";
-import { useStore } from "vuex";
-
-export function useMapGetters<T extends string>(keys: T[]) {
-  const res: Record<string, ComputedRef> = {}
-  // @ts-ignore
-  const { getters } = useStore()
-  keys.map(key => {
-    if (Reflect.has(getters, key)) {
-      res[key] = computed(() => getters[key])
-    }
-  })
-  return res as any as Record<T, ComputedRef>
-}

+ 7 - 3
src/main.ts

@@ -1,7 +1,7 @@
 import { createApp } from "vue";
 import App from "./App.vue";
 import router from "./router";
-import store from "./store";
+import { setupStore } from "/@/store";
 
 import { useElementPlus } from "../src/plugins/element-plus";
 import { useTable } from "../src/plugins/vxe-table";
@@ -50,7 +50,11 @@ export const getServerConfig = async (): Promise<any> => {
 };
 
 getServerConfig().then(async () => {
-  app.use(router);
+  setupStore(app);
+
+  app.use(router).use(useElementPlus).use(useTable).use(usI18n);
+
   await router.isReady();
-  app.use(store).use(useElementPlus).use(useTable).use(usI18n).mount("#app");
+
+  app.mount("#app");
 });

+ 11 - 44
src/router/index.ts

@@ -8,14 +8,10 @@ import nestedRouter from "./modules/nested";
 import errorRouter from "./modules/error";
 import permissionRouter from "./modules/permission";
 import remainingRouter from "./modules/remaining"; //静态路由
-import Layout from "/@/layout/index.vue";
 
-// https://cn.vitejs.dev/guide/features.html#glob-import
-const modulesRoutes = import.meta.glob("/src/views/*/*/*.vue");
-
-import { getAsyncRoutes } from "/@/api/routes";
 import { storageSession } from "../utils/storage";
 import { i18n } from "/@/plugins/i18n/index";
+import { usePermissionStoreHook } from "/@/store/modules/permission";
 
 const constantRoutes: Array<RouteRecordRaw> = [
   homeRouter,
@@ -27,28 +23,19 @@ const constantRoutes: Array<RouteRecordRaw> = [
   errorRouter,
 ];
 
-// 过滤后端传来的动态路由重新生成规范路由
-const addAsyncRoutes = (arrRoutes: Array<string>) => {
-  if (!arrRoutes || !arrRoutes.length) return;
-  arrRoutes.forEach((v: any) => {
-    if (v.redirect) {
-      v.component = Layout;
-    } else {
-      v.component = modulesRoutes[`/src/views${v.path}/index.vue`];
-    }
-    if (v.children) {
-      addAsyncRoutes(v.children);
-    }
-  });
-  return arrRoutes;
-};
-
 // 按照路由中meta下的rank等级升序来排序路由
-function ascending(arr) {
+export const ascending = (arr) => {
   return arr.sort((a: any, b: any) => {
     return a?.meta?.rank - b?.meta?.rank;
   });
-}
+};
+
+// 将所有静态路由导出
+export const constantRoutesArr = ascending(constantRoutes).concat(
+  ...remainingRouter
+);
+
+export const isLogin = storageSession.getItem("info");
 
 const router = createRouter({
   history: createWebHashHistory(),
@@ -73,29 +60,9 @@ import NProgress from "../utils/progress";
 const whiteList = ["/login", "/register"];
 
 router.beforeEach((to, _from, next) => {
-  let isLogin = storageSession.getItem("info");
   // _from?.name;
   if (isLogin) {
-    // 异步路由
-    getAsyncRoutes({ name: isLogin.username }).then(({ info }) => {
-      if (info.length === 0) {
-        return;
-      }
-      addAsyncRoutes([info]).forEach((v: any) => {
-        // 防止重复添加路由
-        if (
-          router.options.routes.findIndex((value) => value.path === v.path) !==
-          -1
-        )
-          return;
-        // 切记将路由push到routes后还需要使用addRoute,这样路由才能正常跳转
-        router.options.routes.push(v);
-        // 最终路由进行升序
-        ascending(router.options.routes);
-        router.addRoute(v.name, v);
-      });
-    });
-    console.log(router.options.routes);
+    usePermissionStoreHook().changeSetting();
   }
   NProgress.start();
   const { t } = i18n.global;

+ 10 - 10
src/router/modules/components.ts

@@ -19,7 +19,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/video/index.vue"),
       meta: {
         title: "message.hsvideo",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -29,7 +29,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/map/index.vue"),
       meta: {
         title: "message.hsmap",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -39,7 +39,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/draggable/index.vue"),
       meta: {
         title: "message.hsdraggable",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -50,7 +50,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/split-pane/index.vue"),
       meta: {
         title: "message.hssplitPane",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -60,7 +60,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/button/index.vue"),
       meta: {
         title: "message.hsbutton",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -70,7 +70,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/cropping/index.vue"),
       meta: {
         title: "message.hscropping",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -80,7 +80,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/count-to/index.vue"),
       meta: {
         title: "message.hscountTo",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -90,7 +90,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/selector/index.vue"),
       meta: {
         title: "message.hsselector",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -100,7 +100,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/seamless-scroll/index.vue"),
       meta: {
         title: "message.hsseamless",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -110,7 +110,7 @@ const componentsRouter = {
       component: () => import("/@/views/components/contextmenu/index.vue"),
       meta: {
         title: "message.hscontextmenu",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },

+ 1 - 1
src/router/modules/editor.ts

@@ -19,7 +19,7 @@ const editorRouter = {
       component: () => import("/@/views/editor/index.vue"),
       meta: {
         title: "message.hseditor",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },

+ 2 - 2
src/router/modules/error.ts

@@ -19,7 +19,7 @@ const errorRouter = {
       component: () => import("/@/views/error/401.vue"),
       meta: {
         title: "message.hsfourZeroOne",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },
@@ -29,7 +29,7 @@ const errorRouter = {
       component: () => import("/@/views/error/404.vue"),
       meta: {
         title: "message.hsfourZeroFour",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },

+ 1 - 1
src/router/modules/flowchart.ts

@@ -19,7 +19,7 @@ const flowChartRouter = {
       component: () => import("/@/views/flow-chart/index.vue"),
       meta: {
         title: "message.hsflowChart",
-        showLink: false,
+        showLink: true,
         savedPosition: true,
       },
     },

+ 0 - 6
src/store/getters.ts

@@ -1,6 +0,0 @@
-const getters = {
-  sidebar: (state: any) => state.app.sidebar,
-  device: (state: any) => state.app.device,
-}
-
-export default getters

+ 8 - 11
src/store/index.ts

@@ -1,12 +1,9 @@
-import { createStore } from 'vuex'
-import getters from './getters'
-import app from './modules/app'
-import settings from './modules/settings'
+import type { App } from "vue";
+import { createPinia } from "pinia";
+const store = createPinia();
 
-export default createStore({
-  getters,
-  modules: {
-    app,
-    settings
-  }
-})
+export function setupStore(app: App<Element>) {
+  app.use(store);
+}
+
+export { store };

+ 56 - 50
src/store/modules/app.ts

@@ -1,58 +1,64 @@
-import { storageLocal } from "../../utils/storage"
-interface stateInter {
-  sidebar: {
-    opened: Boolean,
-    withoutAnimation: Boolean
-  },
-  device: String
-}
+import { storageLocal } from "../../utils/storage";
+import { defineStore } from "pinia";
+import { store } from "/@/store";
 
-const state = {
+interface AppState {
   sidebar: {
-    opened: storageLocal.getItem('sidebarStatus') ? !!+storageLocal.getItem('sidebarStatus') : true,
-    withoutAnimation: false
-  },
-  device: 'desktop'
+    opened: Boolean;
+    withoutAnimation: Boolean;
+  };
+  device: String;
 }
 
-const mutations = {
-  TOGGLE_SIDEBAR: (state: stateInter): void => {
-    state.sidebar.opened = !state.sidebar.opened
-    state.sidebar.withoutAnimation = false
-     if (state.sidebar.opened) {
-      storageLocal.setItem('sidebarStatus', 1)
-    } else {
-      storageLocal.setItem('sidebarStatus', 0)
-    }
+export const useAppStore = defineStore({
+  id: "pure-app",
+  state: (): AppState => ({
+    sidebar: {
+      opened: storageLocal.getItem("sidebarStatus")
+        ? !!+storageLocal.getItem("sidebarStatus")
+        : true,
+      withoutAnimation: false,
+    },
+    device: "desktop",
+  }),
+  getters: {
+    getSidebarStatus() {
+      return this.sidebar.opened;
+    },
+    getDevice() {
+      return this.device;
+    },
   },
-  CLOSE_SIDEBAR: (state: stateInter, withoutAnimation: Boolean) => {
-    storageLocal.setItem('sidebarStatus', 0)
-    state.sidebar.opened = false
-    state.sidebar.withoutAnimation = withoutAnimation
+  actions: {
+    TOGGLE_SIDEBAR() {
+      this.sidebar.opened = !this.sidebar.opened;
+      this.sidebar.withoutAnimation = false;
+      if (this.sidebar.opened) {
+        storageLocal.setItem("sidebarStatus", 1);
+      } else {
+        storageLocal.setItem("sidebarStatus", 0);
+      }
+    },
+    CLOSE_SIDEBAR(withoutAnimation: Boolean) {
+      storageLocal.setItem("sidebarStatus", 0);
+      this.sidebar.opened = false;
+      this.sidebar.withoutAnimation = withoutAnimation;
+    },
+    TOGGLE_DEVICE(device: String) {
+      this.device = device;
+    },
+    async toggleSideBar() {
+      await this.TOGGLE_SIDEBAR();
+    },
+    closeSideBar(withoutAnimation) {
+      this.CLOSE_SIDEBAR(withoutAnimation);
+    },
+    toggleDevice(device) {
+      this.TOGGLE_DEVICE(device);
+    },
   },
-  TOGGLE_DEVICE: (state: stateInter, device: String) => {
-    state.device = device
-  }
-}
-
-const actions = {
-  // @ts-ignore
-  toggleSideBar({ commit }) {
-    commit('TOGGLE_SIDEBAR')
-  },
-  // @ts-ignore
-  closeSideBar({ commit }, { withoutAnimation }) {
-    commit('CLOSE_SIDEBAR', withoutAnimation)
-  },
-  // @ts-ignore
-  toggleDevice({ commit }, device) {
-    commit('TOGGLE_DEVICE', device)
-  }
-}
+});
 
-export default {
-  namespaced: true,
-  state,
-  mutations,
-  actions
+export function useAppStoreHook() {
+  return useAppStore(store);
 }

+ 74 - 0
src/store/modules/permission.ts

@@ -0,0 +1,74 @@
+import { defineStore } from "pinia";
+import { store } from "/@/store";
+
+import { constantRoutesArr, ascending, isLogin } from "/@/router/index";
+
+import { getAsyncRoutes } from "/@/api/routes";
+import Layout from "/@/layout/index.vue";
+import router from "/@/router/index";
+
+// https://cn.vitejs.dev/guide/features.html#glob-import
+const modulesRoutes = import.meta.glob("/src/views/*/*/*.vue");
+
+// 过滤后端传来的动态路由重新生成规范路由
+const addAsyncRoutes = (arrRoutes: Array<string>) => {
+  if (!arrRoutes || !arrRoutes.length) return;
+  arrRoutes.forEach((v: any) => {
+    if (v.redirect) {
+      v.component = Layout;
+    } else {
+      v.component = modulesRoutes[`/src/views${v.path}/index.vue`];
+    }
+    if (v.children) {
+      addAsyncRoutes(v.children);
+    }
+  });
+  return arrRoutes;
+};
+
+export const usePermissionStore = defineStore({
+  id: "pure-permission",
+  state: () => ({
+    constantRoutes: constantRoutesArr, //静态路由
+    asyncRoutes: [], //动态路由
+    wholeRoutes: [],
+  }),
+  actions: {
+    asyncActionRoutes(routes) {
+      this.wholeRoutes = ascending(this.constantRoutes.concat(routes)).filter(
+        (v) => v.meta.showLink
+      );
+      this.asyncRoutes.push(routes);
+    },
+    async changeSetting() {
+      // 异步路由
+      await getAsyncRoutes({ name: isLogin.username }).then(({ info }) => {
+        if (info.length === 0) {
+          this.wholeRoutes = router.options.routes.filter(
+            (v) => v.meta.showLink
+          );
+          return;
+        }
+        addAsyncRoutes([info]).forEach((v: any) => {
+          // 防止重复添加路由
+          if (
+            router.options.routes.findIndex(
+              (value) => value.path === v.path
+            ) !== -1
+          )
+            return;
+          // 切记将路由push到routes后还需要使用addRoute,这样路由才能正常跳转
+          router.options.routes.push(v);
+          // 最终路由进行升序
+          ascending(router.options.routes);
+          router.addRoute(v.name, v);
+          this.asyncActionRoutes(v);
+        });
+      });
+    },
+  },
+});
+
+export function usePermissionStoreHook() {
+  return usePermissionStore(store);
+}

+ 32 - 21
src/store/modules/settings.ts

@@ -1,27 +1,38 @@
 import defaultSettings from "../../settings";
+import { defineStore } from "pinia";
+import { store } from "/@/store";
 
-const state = {
-  title: defaultSettings.title,
-  fixedHeader: defaultSettings.fixedHeader,
-};
+interface SettingState {
+  title: String;
+  fixedHeader: Boolean;
+}
 
-const mutations = {
-  CHANGE_SETTING: (state: any, { key, value }) => {
-    if (state.hasOwnProperty(key)) {
-      state[key] = value;
-    }
+export const useSettingStore = defineStore({
+  id: "pure-setting",
+  state: (): SettingState => ({
+    title: defaultSettings.title,
+    fixedHeader: defaultSettings.fixedHeader,
+  }),
+  getters: {
+    getTitle() {
+      return this.title;
+    },
+    getFixedHeader() {
+      return this.fixedHeader;
+    },
   },
-};
-
-const actions = {
-  changeSetting({ commit }, data) {
-    commit("CHANGE_SETTING", data);
+  actions: {
+    CHANGE_SETTING({ key, value }) {
+      if (this.hasOwnProperty(key)) {
+        this[key] = value;
+      }
+    },
+    changeSetting(data) {
+      this.CHANGE_SETTING(data);
+    },
   },
-};
+});
 
-export default {
-  namespaced: true,
-  state,
-  mutations,
-  actions,
-};
+export function useSettingStoreHook() {
+  return useSettingStore(store);
+}