Vue 要素テンプレートの動的ルーティングのチュートリアル
序文
最近、企業はバックグラウンド管理システムを早急に開発する必要があります。インターネットでいろいろ比較した結果、vue-element-admin は非常に使いやすく強力だと思いますが、実際のビジネスでは使用されない多くの機能が統合されています。 vueの基本バージョン- 要素テンプレートは適切です。メニューの権限の開発を統合し、異なるユーザーがログインするときに異なるメニューを表示するのに少し問題があります。Baidu は長い間探してきましたが、役に立ちませんでした。最後に、私は以下の偉人のソリューションを参照し、私のプロジェクトの実際の完成度を組み合わせてください。
Vue-admin-template の動的ルーティングの実装
キーポイント
一般的な管理システムで動的メニュー権限を実装するには、主に 2 つの方法があります。
1 つ目: フロントエンドには、ログイン、404、ホームページ、その他のルーティング情報などの表示可能な固定ルーティング テーブルのみがあり、バックグラウンドで返されます。その後、ルーティング テーブルに動的に追加されます。
2 番目: フロントエンドには完全なルーティング テーブルがあり、バックグラウンドはユーザーのロールを返します。たとえば、メニューに ['admin', 'user'] がある場合、バックグラウンドによって返される権限情報にはロール情報 ['admin] が含まれます。 '] メニューを表示します。
この記事で最初に実装したのは、視聴する前に自分のプロジェクトを比較することです。
多くを語らず、ただ始めてください。
バックグラウンドで返されるデータ形式について
これは、標準化のために返される必要があるメニュー データ形式であり、この記事の以降の部分でも必要になります。返されるデータ形式とフィールド名は、開発中にバックグラウンド ブラザーで定義するのが最善です。
[
{
path: '/example',
component: 'Layout',
redirect: '/example',
name: '权限管理-test',
alwaysShow: true,
meta: {
title: '权限管理-test', icon: 'el-icon-s-help'},
children: [
{
path: 'table',
name: '用户',
component:'views/permission/user',
meta: {
title: '用户', icon: 'table'}
},
{
path: 'tree',
name: '角色',
component: 'views/tree/index',
meta: {
title: '角色', icon: 'tree'}
}
]
},
]
これは、プロジェクトのバックグラウンドによって返されたデータ形式です。バックグラウンドが仕事を辞めたため、フィールド名と形式について合意する時間がありませんでした。標準形式と比較して、バックグラウンドがパス フィールドという名前を付けていることがわかりました。ルーター、メタの欠落、リダイレクト フィールドの欠落など、ここでは上記の標準形式に処理する必要があります。
"data": [
{
"children": [
{
"children": [],
"code": "",
"component": "views/user-Management/index",
"icon": "table",
"id": "4",
"name": "用户管理",
"pid": "1",
"remark": "菜单",
"router": "user",
"sort": 4,
"type": 2
}
],
"code": "",
"component": "Layout",
"icon": "el-icon-s-help",
"id": "1",
"name": "平台管理",
"pid": "0",
"remark": "目录",
"router": "/user-Management",
"sort": 1,
"type": 1
}
],
まず、バックグラウンドから返される権限情報を取得するために getRoutes を追加します。
次のように、getRoutes を src/api/user.js ファイルの最後に直接追加します。
export function getRoutes() {
return request({
url: '/user/ownMenu', //这里换成自己的请求后台获取权限信息的接口
method: 'get'
})
}
次に、ルーターの下で inde ファイルを処理します。
src/router/index.jsを調整する
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
/* Layout */
import Layout from '@/layout'
// constantRoutes 是公共路由,不管哪个用户都可以看见
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: 'dashboard' }
}]
}
]
// asyncRoutes 是动态的,后台返回哪些就只有哪些。
export const asyncRoutes = [
// 404 必须添加
{
path: '*', redirect: '/404', hidden: true }
]
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({
y: 0 }),
routes: constantRoutes
})
const router = createRouter()
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
export default router
3 番目に、許可処理メカニズムを追加します。
src/store/modules/permission.js ファイルを作成します。
import {
constantRoutes } from '@/router' // 引入路由表里的固定路由
import {
getRoutes } from '@/api/user' // 引入第一步创建的获取权限信息的接口
import Layout from '@/layout' // 引入布局
// 映射路由表,二级菜单component的值为字符串,但是在这里要映射一下它们的实际位置。
const componentsMap = {
// 平台管理
'views/user-Management/index': () => import('@/views/user-Management/index')
}
/**
* 把后台返回菜单组装成routes要求的格式
*/
export function getAsyncRoutes(routes) {
const res = []
const keys = ['path', 'name', 'children', 'redirect', 'alwaysShow', 'meta', 'hidden']
routes.forEach(item => {
const newItem = {
}
if (item.component) {
if (item.component === 'Layout') {
newItem.component = Layout
} else {
newItem['component'] = componentsMap[item.component]
}
}
for (const key in item) {
if (keys.includes(key)) {
newItem[key] = item[key]
}
}
if (newItem.children) {
newItem.children = getAsyncRoutes(item.children)
}
res.push(newItem)
})
return res
}
export function getMenuListData(menuList) {
// 我自己的,后台返回的数据格式和标准格式一致的就去掉这个方法就行
for (let i = 0; i < menuList.length; i++) {
if (menuList[i].children.length > 0) {
menuList[i].redirect = menuList[i].router + '/' + menuList[i].children[0].router
menuList[i].path = menuList[i].router
menuList[i].meta = {
title: menuList[i].name,
icon: menuList[i].icon
}
menuList[i].name = menuList[i].router
getMenuListData(menuList[i].children)
} else {
menuList[i].path = menuList[i].router
menuList[i].meta = {
title: menuList[i].name,
icon: menuList[i].icon
}
menuList[i].name = menuList[i].router
}
}
return menuList
}
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(async resolve => {
const routes = await getRoutes() // 接口获取到后台返回的权限信息,包含路由
const asyncRoutesFront = getMenuListData(routes.data) //这里是因为我返回的格式有点问题,后台暂时没法改,没办法先这么处理了下,返回和标准格式一致的,请直接const asyncRoutes = getAsyncRoutes(routes.data)
const asyncRoutes = getAsyncRoutes(asyncRoutesFront) // 对路由格式进行处理
commit('SET_ROUTES', asyncRoutes)
resolve(asyncRoutes)
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
4番目に、ストアに許可を掛けます
src/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'
import permission from './modules/permission' // 把第三步建好的文件挂上去
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app,
settings,
user,
permission
},
getters
})
export default store
5 番目に、パーミッション インターセプターを調整します。
src/permission.js を変更します。正しいパスに注意してください。これは、3 番目の手順で追加した src/store/modules/permission.js ファイルではありません。
import router, {
constantRoutes } from './router' // 这里把constantRoutes 引入进来
import store from './store'
import {
Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {
getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({
showSpinner: false })
const whiteList = ['/login']
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 hasGetUserInfo = store.getters.name
if (hasGetUserInfo) {
next()
} else {
try {
await store.dispatch('user/getInfo')
// 这里调用的就是第三步新建的generateRoutes
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
router.options.routers = constantRoutes.concat(accessRoutes) // 这一步必须写,不然会出现左侧菜单空白、刷新空白等问题
router.addRoutes(accessRoutes)
next({
...to, replace: true })
// next()
} 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()
})
6 番目に、getter.js を調整し、動的ルーティングを追加します。
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,
// 动态路由
permission_routes: state => state.permission.routes
}
export default getters
7番目に、メニューコンポーネントページを変更します。
src/layout/components/Sidebar/index.vueを変更します
<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', // 动态路由
'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 動的ルーティングの実装 という記事から引用しています。記憶を強化するために自分で書いてください。ありがとう、兄貴。