vue-admin-template 动态路由的实现示例

提供登录与获取用户信息数据接口

在api/user.js中

import request from '@/utils/request'
const Api = {
  TakeOut: '/student/students/takeOut/',
  LoginIn: '/student/students/loginIn/',
  StudentInfo:'/student/students/studentInfo/',
}
export function login(parameter) {
  return request({
    url: Api.LoginIn,
    method: 'get',
    params: parameter
  })
}

export function getInfo(token) {
  return request({
    url: Api.StudentInfo,
    method: 'get',
    params: {'token':token}
  })
}

export function logout() {
  return request({
    url: Api.TakeOut,
    method: 'get'
  })
}

登录接口数据

{'code': 200, 'data': {'token': 'X-admin'}, 'message': "操作成功"}

退出接口数据

{'code': 200, 'data': 'success', 'message': "操作成功"}

详情接口数据

{
    "code": 200,
    "data": {
        "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        "name": "黄晓果",
        "roles": [
            "editor"
        ]
    }
}

改造router/index.js

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

// 基础路由
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },

  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
      path: 'dashboard',
      name: 'Dashboard',
      component: () => import('@/views/dashboard/index'),
      meta: { title: '首页', icon: 'el-icon-menu' }
    }]
  },
]

/**
 * 动态路由
 */
export const asyncRoutes = [
  {
    path: '/studentinformation',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/studentinformation/index'),
        meta: { title: '学生信息', icon: 'el-icon-s-check' }
      }
    ]
  },
  {
    path: '/lecturerinformation',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/lecturerinformation/index'),
        meta: { title: '讲师信息', icon: 'el-icon-s-custom', roles: ['editor'] }
      }
    ]
  },
  {
    path: '/coursemanage',
    component: Layout,
    meta: { roles: ['admin'] },
    children: [
      {
        path: 'index',
        component: () => import('@/views/coursemanage/index'),
        meta: { title: '课程管理', icon: 'el-icon-s-platform'}
      }
    ]
  },
  // 404 页面必须放置在最后一个页面
  { path: '*', redirect: '/404', hidden: true }
]

const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router

将动态显示的路由写在asyncRoutes 中并添加 roles ,例如meta: { roles: [‘admin'] },

在store/modulds目录下添加permission.js

import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

修改store/modulds/user.js

import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('验证失败,请重新登录')
        }

        const {roles, name, avatar } = data
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        commit('SET_ROLES', [])
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      commit('SET_ROLES', [])
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

添加roles: [] 保存权限列表 ,添加内容如下

const getDefaultState = () => {
  return {
    ...
    roles: []
  }
}

const mutations = {
  ...
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        ...
        const {roles, name, avatar } = data
        commit('SET_ROLES', roles)
        ...
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        ...
        commit('SET_ROLES', [])
        ...
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      ...
      commit('SET_ROLES', [])
      ...
    })
  }
}

在store/getters.js中添加roles

const getters = {
  sidebar: state => state.app.sidebar,
  device: state => state.app.device,
  token: state => state.user.token,
  avatar: state => state.user.avatar,
  name: state => state.user.name,

  //添加roles
  roles: state => state.user.roles,
  //动态路由
  permission_routes: state => state.permission.routes,
}
export default getters

将permission添加到store/index.js中

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'

//添加permission
import permission from './modules/permission'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app,
    settings,
    user,

 //添加permission
    permission
  },
  getters
})

export default store

最后修改根目录下的permission.js

import router, { constantRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')
          console.log(roles)
          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          // dynamically add accessible routes
          router.options.routes = constantRoutes.concat(accessRoutes)
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

将数据绑定到nav导航栏上

在layout/components/sidebar/index.vue中

...mapGetters([
      // 动态路由 增加permission_routes
      'permission_routes',
      'sidebar'
    ]),

 <!-- 动态路由 -->
 <sidebar-item v-for="route in permission_routes" :key="route.path" :item="route" :base-path="route.path" />

全部代码如下:

<template>
  <div :class="{ 'has-logo': showLogo }">
    <logo v-if="showLogo" :collapse="isCollapse" />
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :background-color="variables.menuBg"
        :text-color="variables.menuText"
        :unique-opened="false"
        :active-text-color="variables.menuActiveText"
        :collapse-transition="false"
        mode="vertical"
      >
        <!-- <sidebar-item
          v-for="route in routes"
          :key="route.path"
          :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>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Logo from './Logo'
import SidebarItem from './SidebarItem'
import variables from '@/styles/variables.scss'

export default {
  components: { SidebarItem, Logo },
  computed: {
    ...mapGetters([
      // 动态路由 增加permission_routes
      'permission_routes',
      'sidebar',
    ]),
    routes() {
      return this.$router.options.routes
    },
    activeMenu() {
      const route = this.$route
      const { meta, path } = route
      // if set path, the sidebar will highlight the path you set
      if (meta.activeMenu) {
        return meta.activeMenu
      }
      return path
    },
    showLogo() {
      return this.$store.state.settings.sidebarLogo
    },
    variables() {
      return variables
    },
    isCollapse() {
      return !this.sidebar.opened
    },
  },
}
</script>

到此这篇关于vue-admin-template 动态路由的实现的文章就介绍到这了,更多相关vue-admin-template 动态路由的实现内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • vue-admin-template配置快捷导航的代码(标签导航栏)

    vue-element-admin有关快捷导航说明 1.添加标签 @/layout/components/AppMain.vue添加: <template> <section class="app-main"> <transition name="fade-transform" mode="out-in"> <keep-alive :include="cachedViews">

  • 详解使用vue-admin-template的优化历程

    前言 公司有好几个项目都有后台管理系统,为了方便开发,所以选择了 vue 中比较火的后台模板作为基础模板进行开发.但是,开始用的时候,作者并没有对此进行优化,到项目上线的时候,才发现,打包出来的文件都十分之大,就一个 vendor 就有 770k 的体积(下图是基础模板,什么都没加打包后的文件信息): 通过 webpack-bundle-analyzer 进行分析可得,体积主要来源于饿了么UI(体积为 500k),因为没对其进行部分引入拆分组件,导致 webpack 把整个组件库都打包进去了.其

  • Vue实现动态路由导航的示例

    目录 1.导航守卫 二.功能展示 三.原理 四.功能实现 小结 1.导航守卫 “导航” 表示路由正在发生改变 正如其名,vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航.有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的. 记住参数或查询的改变并不会触发进入/离开的导航守卫.你可以通过观察 $route 对象来应对这些变化,或使用 beforeRouteUpdate 的组件内守卫. v-router官网:https://router.vuejs.org

  • vue iview实现动态路由和权限验证功能

    github上关于vue动态添加路由的例子很多,本项目参考了部分项目后,在iview框架基础上完成了动态路由的动态添加和菜单刷新.为了帮助其他需要的朋友,现分享出实现逻辑,欢迎一起交流学习. Github地址 iview-dynamicRouter 实现目标 客户端从服务端拿到路由和权限数据后,刷新项目的路由和菜单列表,并进行权限控制. 项目基础 基础框架: iview组件库官方模板项目 iview-admin 的template分支项目,此项目为 iview-admin 的基础框架代码.项目地

  • Vue Router 实现动态路由和常见问题及解决方法

    个人理解:动态路由不同于常见的静态路由,可以根据不同的「因素」而改变站点路由列表.常见的动态路由大都是用来实现:多用户权限系统不同用户展示不同导航菜单. 如何利用Vue Router 实现动态路由 Vue项目实现动态路由的方式大体可分为两种: 前端将全部路由规定好,登录时根据用户角色权限来动态展示路由: 路由存储在数据库中,前端通过接口获取当前用户对应路由列表并进行渲染: 第一种方式在很多Vue UI Admin上都实现了,可以去读一下他们的源码理解具体的实现思路,这里就不过多展开.第二种方式现

  • vue-admin-template 动态路由的实现示例

    提供登录与获取用户信息数据接口 在api/user.js中 import request from '@/utils/request' const Api = { TakeOut: '/student/students/takeOut/', LoginIn: '/student/students/loginIn/', StudentInfo:'/student/students/studentInfo/', } export function login(parameter) { return

  • Vue 配合eiement动态路由,权限验证的方法

    1.要实现动态路由,只需要在main.js中将所有路由表先规定好,如下 const routes=[ {path:'/login',component:login},/*登录*/ {path:'/home',component:home},/*首页*/ {path:'/monitor',component:monitor},/*实时监控*/ {path: "/orderQuery", component: orderQuery},/*电子围栏*/ {path: "/fence

  • vue+element实现动态换肤的示例代码

    有时候一个项目的主题并不能满足所有人的审美,这时候换肤功能就很友好,本项目基于vue+element实现后台管理项目的换肤功能 1.创建换肤组件 <template> <el-color-picker class="theme-picker" popper-class="theme-picker-dropdown" v-model="theme" :predefine="predefineColors" &g

  • vue系列之动态路由详解【原创】

    开题 最近用vue来构建了一个小项目,由于项目是以iframe的形式嵌套在别的项目中的,所以对于登录的验证就比较的麻烦,索性后端大佬们基于现在的问题提出了解决的方案,在看到他们的解决方案之前,我先画了一个比较标准的单系统的解决方案. 本文目录: 一: 设想 二: 讨论 三:实现 四:总结 一: 设想 简单解释下上图就是: 首先前端从cookie获取token,如果没有token就跳转到登录页面登录,登录验证之后生成token存在数据库中并返回给前端:前端将这个token保存下来,为了让在浏览器新

  • vue中template的三种写法示例

    第一种(字符串模板写法): 直接写在vue构造器里,这种写法比较直观,适用于html代码不多的场景,但是如果模板里html代码太多,不便于维护,不建议这么写. <!DOCTYPE html> <html> <!-- WARNING! Make sure that you match all Quasar related tags to the same version! (Below it's "@1.7.4") --> <head> &

  • Vue--Router动态路由的用法示例详解

    目录 官网网址 动态路由概述 同一路由多个参数 path-to-regexp Api用法 1. pathToRegexp() 2.exec() 3. parse() 4. compile() 本文介绍Vue-Router中动态路由的用法. 官网网址 Vue官网:带参数的动态路由匹配 | Vue Router 动态路由概述 说明 很多时候,我们需要将给定匹配模式的路由映射到同一个组件.例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但用户 ID 不同.在 Vue Router 中,

  • vue router动态路由下让每个子路由都是独立组件的解决方案

    vue-router 之动态路由 vue-router官网上面是这样说的 // 带查询参数,变成 /register?plan=private router.push({ path: 'register', query: { plan: 'private' }}) 然后,我就这样写了: this.$router.push({path:'manage', query: {id: 'tasklist'}})1 结果很明显,失败了.然后我就默默的再次看了一下官网,结果发现了这句话 // 命名的路由 r

随机推荐