1、关闭mock

注释掉main.js第16行

// with polyfills
import 'core-js/stable'
import 'regenerator-runtime/runtime'

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/'
import i18n from './locales'
import { VueAxios } from './utils/request'
import ProLayout, { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import themePluginConfig from '../config/themePluginConfig'

// mock
// WARNING: `mockjs` NOT SUPPORT `IE` PLEASE DO NOT USE IN `production` ENV.
// import './mock'  // 注释掉本行

import bootstrap from './core/bootstrap'
2、修改动态权限功能引用

src/store/index.js,注释掉第8行,放开第11行

import Vue from 'vue'
import Vuex from 'vuex'

import app from './modules/app'
import user from './modules/user'

// default router permission control
// import permission from './modules/permission' // 注释掉本行

// dynamic router permission control (Experimental)
import permission from './modules/async-router'  // 放开本行
import getters from './getters'
4、修改报错

此时会出现如下错误:

ERROR  Failed to compile with 2 errors                                                                                                                     10:12:09
These dependencies were not found:

* @/utils/permissions in ./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--12-0!./node_modules/_babel-loader@8.2.2@babel-loader/lib!./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--0-0!./node_modules/_vue-loader@15.9.6@vue-loader/lib??vue-loader-options!./src/views/role/RoleList.vue?vue&type=script&lang=js&
* @/views/account/settings/BaseSetting in ./src/router/generator-routers.js

To install them, you can run: npm install --save @/utils/permissions @/views/account/settings/BaseSetting
1、新建@/utils/permissions.js文件,内容如下:
因为,/src/views/role/RoleList.vue中引用了这个文件的actionToObject函数,但是缺失所以报错。暂时先给补上,后续逻辑自己实现即可。
export function actionToObject (data) {
  return data
}
2./src/router/generator-routers.js文件注释掉第49// 'BaseSettings': () => import('@/views/account/settings/BaseSetting'),
5、修改src/api/login.js
# 将url修改为自己项目的URL
const userApi = {
  Login: '/lab/portal/login',
  Logout: '/lab/portal/logout',
  ForgePassword: '/lab/portal/forge-password',
  Register: '/lab/portal/register',
  twoStepCode: '/lab/portal/2step-code',
  SendSms: '/lab/portal/account/sms',
  SendSmsErr: '/lab/portal/account/sms_err',
  // get my info
  UserInfo: '/lab/portal/userInfo',
  UserMenu: '/lab/portal/user/nav'
}
6、修改permission.js逻辑

框架原来的逻辑是

1、登录,获取token

2、访问GetInfo方法,拿到用户角色信息

3、访问GenerateRoutes,根据角色信息获取路由信息。

给他精简为两步,1、登录获取token,2、访问getInfo方法拿到用户角色、权限等全部信息

# 改成这样样子

		// check login user.roles is null
      if (store.getters.roles.length === 0) {
        // request login userInfo
        store.dispatch('GetInfo').then(res => {
              // 动态添加可访问路由表
              router.addRoutes(store.getters.addRouters)
              // 请求带有 redirect 重定向时,登录自动重定向到该地址
              const redirect = decodeURIComponent(from.query.redirect || to.path)
              if (to.path === redirect) {
                // set the replace: true so the navigation will not leave a history record
                next({ ...to, replace: true })
              } else {
                // 跳转到目的路由
                next({ path: redirect })
              }
          })
          .catch(() => {
            notification.error({
              message: '错误',
              description: '请求用户信息失败,请重试'
            })
            // 失败时,获取用户信息失败时,调用登出,来清空历史保留信息
            store.dispatch('Logout').then(() => {
              next({ path: loginRoutePath, query: { redirect: to.fullPath } })
            })
          })
      } else {
        next()
      }
7、修改src/store/modules/user.js
1import { generatorDynamicRouter } from '@/router/generator-routers'
2、修改GetInfo函数(可根据自己实际情况进行调整)

    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.data
          if (result.role && result.role > 0) {
            commit('SET_ROLES', result.role)
            commit('SET_INFO', result)
            commit('SET_ROUTERS', generatorDynamicRouter(result.routes))
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }

          commit('SET_NAME', { name: result.name, welcome: welcome() })
          commit('SET_AVATAR', result.avatar)

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    }
8、修改generatorDynamicRouter

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (jsonRouter) => {
  const routers = generator(jsonRouter)// labRouterMap
  routers.push(notFoundRouter)
  return routers
}

#根据后台传回来的json自行调整具体数据
/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    // const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item.meta || {}
    const currentRouter = {
      // 如果路由设置了 path,则作为默认 path,否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${parent && parent.path || ''}/${item.path}`,
      // 路由名称,建议唯一
      name: item.name || '',
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      component: (constantRouterComponents[item.component.data]) || (() => import(`@/views/${item.component.data}`)),
		//注意,这个@后面一定要跟一个views或者其他的字符串,否则编译会检查md文件异常
      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用,可去掉)
      meta: {
        title: item.meta.title,
        icon: item.meta.icon || undefined
      }
    }
    // 是否设置了隐藏菜单
    if (item.hidden === true) {
      currentRouter.hidden = true
    }

    // 为了防止出现后端返回结果不规范,处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单,并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}


Logo

前往低代码交流专区

更多推荐