vue-admin-template?動(dòng)態(tài)路由的實(shí)現(xiàn)示例
提供登錄與獲取用戶(hù)信息數(shù)據(jù)接口
在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' }) }
登錄接口數(shù)據(jù)
{'code': 200, 'data': {'token': 'X-admin'}, 'message': "操作成功"}
退出接口數(shù)據(jù)
{'code': 200, 'data': 'success', 'message': "操作成功"}
詳情接口數(shù)據(jù)
{ "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' // 基礎(chǔ)路由 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: '首頁(yè)', icon: 'el-icon-menu' } }] }, ] /** * 動(dòng)態(tài)路由 */ export const asyncRoutes = [ { path: '/studentinformation', component: Layout, children: [ { path: 'index', component: () => import('@/views/studentinformation/index'), meta: { title: '學(xué)生信息', 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 頁(yè)面必須放置在最后一個(gè)頁(yè)面 { 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
將動(dòng)態(tài)顯示的路由寫(xiě)在asyncRoutes 中并添加 roles ,例如meta: { roles: [‘a(chǎn)dmin'] },
在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('驗(yàn)證失敗,請(qǐng)重新登錄') } 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: [] 保存權(quán)限列表 ,添加內(nèi)容如下
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, //動(dòng)態(tài)路由 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() })
將數(shù)據(jù)綁定到nav導(dǎo)航欄上
在layout/components/sidebar/index.vue中
...mapGetters([ // 動(dòng)態(tài)路由 增加permission_routes 'permission_routes', 'sidebar' ]), <!-- 動(dòng)態(tài)路由 --> <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([ // 動(dòng)態(tài)路由 增加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>
到此這篇關(guān)于vue-admin-template 動(dòng)態(tài)路由的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)vue-admin-template 動(dòng)態(tài)路由的實(shí)現(xiàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue父組件與子組件之間的數(shù)據(jù)交互方式詳解
最近一直在做一個(gè)vue移動(dòng)端商城的實(shí)戰(zhàn),期間遇到一個(gè)小小的問(wèn)題,值得一說(shuō),下面這篇文章主要給大家介紹了關(guān)于vue父組件與子組件之間數(shù)據(jù)交互的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11require.js 加載 vue組件 r.js 合并壓縮的實(shí)例
這篇文章主要介紹了require.js 加載 vue組件 r.js 合并壓縮的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-10-10vue 的點(diǎn)擊事件獲取當(dāng)前點(diǎn)擊的元素方法
今天小編就為大家分享一篇vue 的點(diǎn)擊事件獲取當(dāng)前點(diǎn)擊的元素方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09Vue-cli3中如何引入ECharts并實(shí)現(xiàn)自適應(yīng)
這篇文章主要介紹了Vue-cli3中如何引入ECharts并實(shí)現(xiàn)自適應(yīng),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06vue無(wú)法加載文件C:\xx\AppData\Roaming\npm\vue.ps1系統(tǒng)禁止運(yùn)行腳本
這篇文章主要介紹了vue?:?無(wú)法加載文件?C:\xx\AppData\Roaming\npm\vue.ps1...系統(tǒng)上禁止運(yùn)行腳本問(wèn)題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07Vant?Weapp組件picker選擇器初始默認(rèn)選中問(wèn)題
這篇文章主要介紹了Vant?Weapp組件picker選擇器初始默認(rèn)選中問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01vue + element-ui實(shí)現(xiàn)簡(jiǎn)潔的導(dǎo)入導(dǎo)出功能
Element-UI是餓了么前端團(tuán)隊(duì)推出的一款基于Vue.js 2.0 的桌面端UI框架,手機(jī)端有對(duì)應(yīng)框架是 Mint UI,下面這篇文章主要給大家介紹了關(guān)于利用vue + element-ui如何實(shí)現(xiàn)簡(jiǎn)潔的導(dǎo)入導(dǎo)出功能的相關(guān)資料,需要的朋友可以參考下。2017-12-12