Procházet zdrojové kódy

按钮路由配置

quwangxin před 3 roky
rodič
revize
bc0cc36fe1

+ 1 - 0
package.json

@@ -34,6 +34,7 @@
     "vue": "^2.7.10",
     "vue-clipboard2": "^0.3.3",
     "vue-countup-v2": "^4.0.0",
+    "vuex-persistedstate": "^4.1.0",
     "vue-echarts": "^6.2.3",
     "vue-i18n": "^8.27.2",
     "vue-router": "^3.6.4",

+ 6 - 15
src/api/layout/index.js

@@ -1,20 +1,11 @@
 import request from '@/utils/request';
-import { res1111 } from './router';
-import { res222 } from './router2';
 
 /**
- * 获取当前登录的用户信息、菜单、权限、角色
+ * 获取当前登录的菜单、按钮权限
  */
-export async function getUserInfo() {
-   const res = await request.get('/system/resources/getResourcesTree');
-   console.log('res--',res)
-  // if (res1111.code === 0 && res1111.data) {
-  //   return res1111.data;
-  // }
-  // if (res222.code == 0 && res222.data) {
-  //   return res222.data;
-  // }
-  if (res.data.code == 0 && res.data.data) { 
+export async function getResourcesTree () {
+  const res = await request.get('/system/resources/getResourcesTree');
+  if (res.data.code == 0 && res.data.data) {
     return res.data.data;
   }
   return Promise.reject(new Error(res.data.message));
@@ -23,7 +14,7 @@ export async function getUserInfo() {
 /**
  * 修改当前登录的用户密码
  */
-export async function updatePassword(data) {
+export async function updatePassword (data) {
   const res = await request.put('/auth/password', data);
   if (res.data.code === 0) {
     return res.data.message ?? '修改成功';
@@ -34,7 +25,7 @@ export async function updatePassword(data) {
 /**
  * 查询未读通知
  */
-export async function getUnreadNotice() {
+export async function getUnreadNotice () {
   return {
     notice: [
       {

+ 5 - 3
src/router/index.js

@@ -14,7 +14,7 @@ Vue.use(VueRouter);
 const router = new VueRouter({
   routes,
   mode: 'history',
-  scrollBehavior() {
+  scrollBehavior () {
     return { y: 0 };
   }
 });
@@ -32,9 +32,11 @@ router.beforeEach((to, from, next) => {
     if (!store.state.user.menus) {
       store
         .dispatch('user/fetchUserInfo')
-        .then(({ menus, homePath }) => {
+        .then(({ menus, homePath, authoritiesRouter }) => {
           if (menus) {
-            router.addRoute(getMenuRoutes(menus, homePath));
+            router.addRoute(
+              getMenuRoutes([...menus, ...authoritiesRouter], homePath)
+            );
             next({ ...to, replace: true });
           }
         })

+ 8 - 1
src/store/index.js

@@ -6,6 +6,7 @@ import Vuex from 'vuex';
 import getters from './getters';
 import user from './modules/user';
 import theme from './modules/theme';
+// import createPersistedState from 'vuex-persistedstate';
 
 Vue.use(Vuex);
 
@@ -17,5 +18,11 @@ export default new Vuex.Store({
     user,
     theme
   },
-  getters
+  getters,
+  plugins: [
+    // createPersistedState({
+    //   storage: window.sessionStorage,
+    //   paths: ['']
+    // })
+  ] //会自动保存创建的状态。刷新还在
 });

+ 55 - 11
src/store/modules/user.js

@@ -1,9 +1,39 @@
 /**
  * 登录状态管理
  */
-import { formatMenus, toTreeData, formatTreeData } from 'ele-admin';
+import {
+  formatMenus,
+  toTreeData,
+  formatTreeData,
+  menuToRoute
+} from 'ele-admin';
 import { USER_MENUS } from '@/config/setting';
-import { getUserInfo } from '@/api/layout';
+import { getResourcesTree } from '@/api/layout';
+
+const formatRouter = (list) => {
+  let menuList = []; // menuType
+  let authorities = [];
+
+  const fn = (list) => {
+    let arr = [];
+    for (const p of list) {
+      if (p.menuType === 2) {
+        authorities.push(p);
+      } else {
+        if (p.children?.length) {
+          p.children = fn(p.children);
+        }
+        arr.push(p);
+      }
+    }
+
+    return arr;
+  };
+
+  menuList = fn(list);
+
+  return { menuList, authorities };
+};
 
 export default {
   namespaced: true,
@@ -40,7 +70,7 @@ export default {
      * 请求用户信息、权限、角色、菜单
      */
     // async fetchUserInfo({ commit }) {
-    //   const result = await getUserInfo().catch(() => {});
+    //   const result = await getResourcesTree().catch(() => {});
     //   if (!result) {
     //     return {};
     //   }
@@ -70,19 +100,22 @@ export default {
     // },
     //动态路由
     async fetchUserInfo ({ commit }) {
-      const result = await getUserInfo().catch(() => {});
+      const result = await getResourcesTree().catch(() => {});
       console.log('result--', result);
       if (!result) {
         return {};
       }
-      // 用户信息
-      commit('setUserInfo', result);
+
+      const { menuList, authorities } = formatRouter(result);
+
       // 用户权限
       // const authorities =
       //   result.authorities
       //     ?.filter((d) => !!d.authority)
       //     ?.map((d) => d.authority) ?? [];
-      // commit('setAuthorities', authorities);
+
+      console.log(menuList, authorities);
+      commit('setAuthorities', authorities);
       // 用户角色
       // const roles = result.roles?.map((d) => d.roleCode) ?? [];
       // commit('setRoles', roles);
@@ -90,18 +123,29 @@ export default {
       const { menus, homePath } = formatMenus(
         USER_MENUS ??
           toTreeData({
-            data: result,
-            // data: result?.filter((d) => d.menuType !== 2),  暂时不做按钮权限
+            data: menuList,
             idField: 'id',
             parentIdField: 'parentId'
           })
       );
 
-      // console.log('menus--',menus)
+      const { menus: authoritiesRouter } = formatMenus(
+        USER_MENUS ??
+          toTreeData({
+            data: authorities.filter((i) => i.path),
+            idField: 'id',
+            parentIdField: 'parentId'
+          })
+      );
+      console.log('menus--', menus);
       commit('setMenus', menus);
       // const menus = result;
       // const homePath = '/dashboard/workplace';
-      return { menus, homePath };
+      return {
+        menus,
+        homePath,
+        authoritiesRouter
+      };
     },
 
     /**

+ 11 - 8
src/views/login/index.vue

@@ -115,7 +115,7 @@
     // eslint-disable-next-line vue/multi-word-component-names
     name: 'Login',
     components: { I18nIcon },
-    data() {
+    data () {
       return {
         // 登录框方向, 0居中, 1居右, 2居左
         direction: 0,
@@ -135,7 +135,7 @@
     },
     computed: {
       // 表单验证规则
-      rules() {
+      rules () {
         return {
           loginName: [
             {
@@ -156,22 +156,25 @@
         };
       }
     },
-    created() {
+    created () {
       if (getToken()) {
         this.goHome();
       }
     },
     methods: {
       /* 提交 */
-      submit() {
+      submit () {
         this.$refs.form.validate((valid) => {
           if (!valid) {
             return false;
           }
           this.loading = true;
           login(this.form)
-            .then(res => {
-              localStorage.setItem('userId', res.data.userId)
+            .then((res) => {
+              localStorage.setItem('userId', res.data.userId);
+
+              // 用户信息
+              this.$store.commit('user/setUserInfo', res.data);
               this.loading = false;
               this.$message.success(res.message);
               this.goHome();
@@ -183,11 +186,11 @@
         });
       },
       /* 跳转到首页 */
-      goHome() {
+      goHome () {
         this.$router.push(this.$route?.query?.from ?? '/').catch(() => {});
       },
       /* 更换图形验证码 */
-      changeCaptcha() {
+      changeCaptcha () {
         // 这里演示的验证码是后端返回base64格式的形式, 如果后端地址直接是图片请参考忘记密码页面
         getCaptcha()
           .then((data) => {