loulijun2021
2022-06-26 0d86c19b122011dc528c624597b0952660d69aba
1.优化动态路由
已修改7个文件
446 ■■■■ 文件已修改
src/layout/components/Navbar.vue 27 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/layout/components/Sidebar/index.vue 70 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/permission.js 28 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/router/index.js 104 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/store/modules/permission.js 181 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/store/modules/user.js 34 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/views/login/index.vue 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/layout/components/Navbar.vue
@@ -72,30 +72,9 @@
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      // await this.$store.dispatch('user/logout')
      const usercode = getCookie('navTabId')
      const username = getCookie('admin')
      const usertype = getCookie('usertype')
      const userid = getCookie('userid')
      const data = {
        usercode,
        username,
        usertype,
        userid
      }
      const res = await logout(data)
      if (res.code === '200') {
        removeToken()
        resetRouter()
        removeCookie('admin')
        removeCookie('navTabId')
        removeCookie('usertype')
        removeCookie('userid')
        this.$message.success('退出成功!')
        this.$router.push('/login')
        // this.$router.push(`/login?redirect=${this.$route.fullPath}`)
      }
      // this.$router.push(`/login`)
      await this.$store.dispatch('user/logout')
      this.$message.success('退出成功!')
      this.$router.push(`/login`)
    }
  }
}
src/layout/components/Sidebar/index.vue
@@ -13,14 +13,14 @@
        :collapse-transition="false"
        mode="vertical"
      >
        <sidebar-item
          v-for="route in routes"
          :key="route.path"
          class="el-scrollbar-menu"
          :item="route"
          :base-path="route.path"
        />
        <!--        <sidebar-item v-for="route in permission_routes" :key="route.path" :item="route" :base-path="route.path" />-->
        <!--        <sidebar-item-->
        <!--          v-for="route in routes"-->
        <!--          :key="route.path"-->
        <!--          class="el-scrollbar-menu"-->
        <!--          :item="route"-->
        <!--          :base-path="route.path"-->
        <!--        />-->
        <sidebar-item v-for="route in permission_routes" :key="route.path" :item="route" :base-path="route.path" />
      </el-menu>
    </el-scrollbar>
@@ -47,65 +47,13 @@
      routers: []
    }
  },
  async created() {
    const { data: res } = await LoginMenu()
    this.routers = res
    this.routers.unshift({ code: '1000', name: '系统设置' })
  },
  computed: {
    ...mapGetters([
      'permission_routes',
      'sidebar'
    ]),
    routes() {
      // 接口中的返回值 进行格式化
      const newCodeArr = []
      const newCodeNameArr = []
      this.routers.forEach(item => {
        if (item.code) {
          newCodeArr.push(item.code)
          newCodeNameArr.push({ code: item.code, title: item.name })
          if (item.children) {
            item.children.forEach(it => {
              if (it.code) {
                newCodeArr.push(it.code)
                newCodeNameArr.push({ code: it.code, title: it.name })
              }
            })
          }
        }
      })
      // 本地路由与 接口中的返回值进行匹配,有相同code的值进行push
      const arr = this.$router.options.routes
      const arr2 = []
      arr.forEach((item, index) => {
        if (newCodeArr.includes(item.code) && item.children.length === 1) {
          arr2.push(item)
        } else if (newCodeArr.includes(item.code) && item.children.length > 1) {
          newCodeNameArr.forEach(it1 => { // 替换接口中的name为菜单名称
            if (it1.code === item.code) {
              item.meta.title = it1.title
            }
          })
          const a = []
          item.children.forEach((it2, ind) => { // 遍历
            if (newCodeArr.includes(it2.code)) {
              newCodeNameArr.forEach(it1 => { // 替换接口中的name为菜单名称
                if (it2.code === it1.code) {
                  it2.meta.title = it1.title
                }
              })
              a.push(it2)
            }
          })
          item.children = a
          arr2.push(item)
        }
      })
      return arr2
      // return arr
      return this.$router.options.routes
    },
    activeMenu() {
      const route = this.$route
src/permission.js
@@ -27,39 +27,25 @@
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      console.log(hasGetUserInfo, 1)
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          // await store.dispatch('user/getInfo')
          // next()
          // 拉取info
          // const info = await store.dispatch('user/getInfo')
          // 拉取菜单信息表
          const menu = await store.dispatch('user/getMenu')
          // 生成可访问的路由表
          // await store.dispatch('permission/generateRoutes')
          await store.dispatch('permission/generateRoutes', menu)
          // 动态添加可访问路由表
          // router.addRoutes(store.getters.addRouters)
          router.addRoutes(store.getters.addRouters)
          // hack方法 确保addRoutes已完成
          // next({ ...to, replace: true })
          next({ ...to, replace: true })
          // console.log(store.getters.addRouters, 1)
          // const s = store.getters.addRouters
          // router.addRoutes(s)
          // if (s) {
          //   console.log(s)
          // }
          // const s = store.getters.addRouters
          // router.addRoutes(s)
          //
          // if (s) {
          //   console.log(s, 11111)
          // }
          next()
          // next({ ...to, replace: true })
          // next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
src/router/index.js
@@ -36,7 +36,6 @@
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
@@ -58,14 +57,16 @@
    component: Layout,
    redirect: '/index',
    name: '系统首页',
    code: '1000',
    children: [{
      path: 'index',
      name: 'index',
      component: () => import('@/views/xtsy/index'),
      meta: { title: '系统首页', icon: 'home', affix: true }
    }]
  },
  }
  // { path: '*', redirect: '/404', hidden: true }
]
export const asyncRoutes = [
  {
    path: '/jcsz',
    component: Layout,
@@ -478,103 +479,8 @@
        meta: { title: 'SOP上传', icon: '' }
      }
    ]
  },
  { path: '*', redirect: '/404', hidden: true }
  }
]
// export const constantRoutesxxxxxx = [
//
//   {
//     path: '/login',
//     component: () => import('@/views/login/index'),
//     hidden: true
//   },
//   {
//     path: '/404',
//     component: () => import('@/views/404'),
//     hidden: true
//   },
//
//   {
//     path: '/redirect',
//     component: Layout,
//     hidden: true,
//     children: [
//       {
//         path: '/redirect/:path(.*)',
//         component: () => import('@/views/redirect/index')
//       }
//     ]
//   },
//   {
//     path: '/',
//     component: Layout,
//     redirect: '/dashboard',
//     children: [{
//       path: 'dashboard',
//       name: 'Dashboard',
//       component: () => import('@/views/dashboard/index')
//     }]
//   },
//   {
//     path: '/xtsy',
//     component: Layout,
//     redirect: '/stxy/index',
//     children: [
//       {
//         path: 'index',
//         name: 'Form',
//         component: () => import('@/views/xtsy/index'),
//         meta: { title: '系统首页', icon: 'form', affix: true }
//       }
//     ]
//   },
//   {
//     path: '/jcsz',
//     component: Layout,
//     redirect: '/jcsz/zzjg',
//     name: 'jcsz',
//     meta: { title: '基础设置', icon: 'el-icon-s-help' },
//     children: [
//       {
//         path: 'zzjg',
//         name: 'Table',
//         component: () => import('@/views/jcsz/zzjg'),
//         meta: { title: '组织架构', icon: 'table' }
//       },
//       {
//         path: 'rwgl',
//         name: 'rwgl',
//         component: () => import('@/views/jcsz/rwgl'),
//         meta: { title: '任务管理', icon: 'tree' }
//       }
//     ]
//   },
//   {
//     path: '/zzmx',
//     component: Layout,
//     redirect: '/zzmx/gylx',
//     name: 'zzmx',
//     meta: { title: '制造模型', icon: 'el-icon-s-help' },
//     children: [
//       {
//         path: 'gylx',
//         name: 'gylx',
//         component: () => import('@/views/zzmx/gylx'),
//         meta: { title: '公益路线', icon: 'table' }
//       },
//       {
//         path: 'jpgj',
//         name: 'jpgj',
//         component: () => import('@/views/zzmx/jpgj'),
//         meta: { title: '节拍工价', icon: 'tree' }
//       }
//     ]
//   },
//
// 404 page must be placed at the end !!!
// , {path: '*', redirect: '/404', hidden: true}
// ]
const createRouter = () => new Router({
  // mode: 'history', // require service support
src/store/modules/permission.js
@@ -1,4 +1,4 @@
import { commonRoutes } from '@/router'
import { asyncRoutes, commonRoutes } from '@/router'
import Layout from '@/layout'
// 判断是否有权限
@@ -14,51 +14,49 @@
 * 把后台返回菜单组装成routes要求的格式
 * @param {*} routes
 */
export function getAsyncRoutes(routes) {
  const res = []
export function getAsyncRoutes(routes2, menu) {
  const menuCode = []// 将后端code取出存成数组形式
  menu.forEach(item => {
    menuCode.push(item.code)
    if (item.children && item.children.length > 0) {
      item.children.forEach(it => {
        menuCode.push(it.code)
      })
    }
  })
  const routes = routes2
  const newRoutes = []
  routes.forEach(item => {
    const newItem = {}
    if (item.component) {
      if (item.component === 'Layout') {
        newItem.component = Layout
        newItem.path = item.path
        if (item.redirect) {
          newItem.redirect = item.redirect
    if (menuCode.includes(item.code) && item.children && item.children.length > 0) {
      console.log(item)
      const children = []
      let flag = false// 判断是否有children存进去
      item.children.forEach(it => {
        if (menuCode.includes(it.code)) {
          children.push(it)
          flag = true
        }
        if (item.hidden === '0') {
          newItem.hidden = false
        }
        if (item.hidden === '1') {
          newItem.hidden = true
        }
        if (item.meta) {
          newItem.meta = { title: item.meta.title, icon: item.meta.icon, affix: item.meta.affix === '1' }
        }
      } else {
        newItem.path = item.path
        if (item.name) {
          newItem.name = item.name
        }
        if (item.hidden === '0') {
          newItem.hidden = false
        }
        if (item.hidden === '1') {
          newItem.hidden = true
        }
        newItem.component = (resolve) => require(['@/views' + `${item.component}`], resolve)
        if (item.meta) {
          newItem.meta = { title: item.meta.title, icon: item.meta.icon, affix: item.meta.affix === '1' }
        }
      })
      if (flag) {
        newRoutes.push({
          alwaysShow: item.alwaysShow,
          code: item.code,
          name: item.name,
          path: item.path,
          redirect: item.redirect,
          component: item.component,
          children: children,
          meta: item.meta
        })
      }
    }
    if (item.children && item.children.length) {
      newItem.children = getAsyncRoutes(item.children)
    }
    res.push(newItem)
  })
  return res
  newRoutes.push({ path: '*', redirect: '/404', hidden: true })
  return newRoutes
}
// 过滤出有权限的路由
@@ -89,105 +87,12 @@
}
const actions = {
  generateRoutes({ commit }, info) {
  generateRoutes({ commit }, menu) {
    return new Promise(resolve => {
      // const accessedRoutes
      // getMenuList().then(routes => {
      //   const asyncRoutes = getAsyncRoutes(routes.data) // 对路由格式进行处理
      //   commit('SET_ROUTES', asyncRoutes)
      //   resolve(asyncRoutes)
      // })
      // '0'代表false,'1'代表true
      const routes = [
        {
          path: '/',
          component: 'Layout',
          redirect: '/index',
          children: [{
            path: 'index',
            name: 'index',
            component: '/xtsy/index',
            meta: { title: '系统首页', icon: 'el-icon-house', affix: '1' }
          }]
        },
        {
          path: '/redirect',
          component: 'Layout',
          hidden: '1',
          children: [
            {
              path: '/redirect/:path(.*)',
              component: '/redirect/index'
            }
          ]
        },
        {
          path: '/jcsz',
          component: 'Layout',
          redirect: '/jcsz/zzjg',
          name: 'jcsz',
          meta: { title: '基础设置', icon: 'el-icon-setting' },
          children: [
            {
              path: 'zzjg',
              name: 'Table',
              component: '/jcsz/zzjg',
              meta: { title: '组织架构', icon: '' }
            },
            {
              path: 'yhqd',
              name: 'yhqd',
              component: '/jcsz/yhqd',
              meta: { title: '用户清单', icon: '' }
            },
            {
              path: 'jsqd',
              name: 'jsqd',
              component: '/jcsz/jsqd',
              meta: { title: '角色清单', icon: '' }
            },
            {
              path: 'wldw',
              name: 'wldw',
              component: '/jcsz/wldw',
              meta: { title: '往来单位', icon: '' }
            }
          ]
        },
        {
          path: '/zzmx',
          component: 'Layout',
          redirect: '/zzmx/gylx',
          name: 'zzmx',
          meta: { title: '制造模型', icon: 'el-icon-s-help' },
          children: [
            {
              path: 'gylx',
              name: 'gylx',
              component: '/zzmx/gylx',
              meta: { title: '公益路线', icon: '' }
            },
            {
              path: 'jpgj',
              name: 'jpgj',
              component: '/zzmx/jpgj',
              meta: { title: '节拍工价', icon: '' }
            },
            {
              path: 'test',
              name: 'test',
              component: '/zzmx/test',
              meta: { title: '测试页面', icon: '' }
            }
          ]
        }
      ]
      const asyncRoutes = getAsyncRoutes(routes)
      asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
      commit('SET_ROUTES', asyncRoutes)
      resolve(asyncRoutes)
      const newRoutes = getAsyncRoutes(asyncRoutes, menu)
      console.log(newRoutes, 2)
      commit('SET_ROUTES', newRoutes)
      resolve(newRoutes)
    })
  }
}
src/store/modules/user.js
@@ -1,4 +1,4 @@
import { login, logout, getInfo } from '@/api/user'
import { login, logout, getInfo, LoginMenu } from '@/api/user'
import { getToken, setToken, removeToken, setCookie, removeCookie, getCookie } from '@/utils/auth'
import { resetRouter } from '@/router'
@@ -21,6 +21,9 @@
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
@@ -71,15 +74,33 @@
      })
    })
  },
  // get user menu
  getMenu({ commit, state }) {
    return new Promise((resolve, reject) => {
      LoginMenu().then(res => {
        if (res.code === '200') {
          commit('SET_NAME', res.Message)
          commit('SET_MENU', res.data)
          resolve(res.data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      const usercode = getCookie('navTabId')
      const username = getCookie('admin')
      const usertype = getCookie('usertype')
      const userid = getCookie('userid')
      const data = {
        usercode: getCookie('navTabId'),
        username: getCookie('admin'),
        usertype: getCookie('usertype')
        usercode,
        username,
        usertype,
        userid
      }
      logout(data).then(res => {
@@ -90,9 +111,10 @@
          removeCookie('admin')
          removeCookie('navTabId')
          removeCookie('usertype')
          this.$message.success('退出成功!')
          removeCookie('userid')
        }
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
src/views/login/index.vue
@@ -155,7 +155,7 @@
    }
    return {
      loginForm: {
        username: '张三', // Admin
        username: 'Admin', // Admin
        password: '123456'// 123456
      },
      loginRules: {