前言
在 【Vue框架】Vue路由配置 中的getters.js里,可以看到有一個應用程序的狀態(變量)叫 permission_routes
,這個就是管理前端菜單欄的狀態。具體代碼的介紹,都以注釋的形式來說明。
1、modules\permission.js
1.1 代碼
import { asyncRoutes, constantRoutes } from '@/router'/*** Use meta.role to determine if the current user has permission* @param roles 用戶角色* @param route 路由信息*/
function hasPermission(roles, route) {// 判斷route是否存在meta和meta.rolesif (route.meta && route.meta.roles) {// 判斷當前傳入的角色,是否存在路由的route中return roles.some(role => route.meta.roles.includes(role))} else {return true}
}/*** Filter asynchronous routing tables by recursion* 通過 遞歸 篩選異步路由表* 【將 基礎路由(不含角色權限)和 符合用戶權限的動態路由(需要角色權限)全部存入res】* @param routes asyncRoutes【去看router\index.js中asyncRoutes】* @param roles*/
export function filterAsyncRoutes(routes, roles) {const res = []// routes是在router\index.js定義的路由數組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 = routesstate.routes = constantRoutes.concat(routes) // 用戶角色的動態路由加入到基礎路由中}
}// 用于存儲一系列 觸發改變 應用狀態的方法
const actions = {generateRoutes({ commit }, roles) {return new Promise(resolve => {let accessedRoutesif (roles.includes('admin')) { // 如果roles數組中包含'admin'accessedRoutes = asyncRoutes || [] // 動態路由全部可以訪問,如果asyncRoutes為`undefined`或`null`,則取[]} else {accessedRoutes = filterAsyncRoutes(asyncRoutes, roles) // 遞歸出符合條件的路由}commit('SET_ROUTES', accessedRoutes)resolve(accessedRoutes)})}
}
// 默認導出一個對象,包含了模塊的相關配置
export default {// 設置模塊的命名空間為 `true`,這意味著該模塊中的狀態、mutations、getters、actions將被封裝在命名空間中,以避免和其他模塊的沖突namespaced: true,// 模塊的狀態state,// 模塊的變化方法mutations,// 模塊的行為方法(調用action,觸發mutations,改變state)actions
}
該文件除了定義的routes
路由狀態和addRoutes
動態添加的路由(后續用到的時候在提),主要在actions
中定義了生成路由的行為方法generateRoutes
,根據roles
角色和內置傳入的{ commit }
(context.commit
)獲取router\index.js中定義的一系列路由,簡單說,就是在前端頁面上被訪問的路徑。
補充防忘記:
- new Promise()以及其參數
- 【Vue框架】Vue路由配置 看看路由
- 【Vue框架】Vuex狀態管理
1.2 想法:
在modules\permission.js
中,根據generateRoutes
提前寫好的邏輯來判斷查回用戶的權限是否符合,這樣不利于添加新角色的改動。
應該都得從數據庫中查詢,得到庫中的角色和每個動態路由。(個人猜想,后續在嘗試)
2、layout\components\Sidebar
2.1 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 permission_routes" :key="route.path" :item="route" :base-path="route.path" /></el-menu></el-scrollbar></div>
</template><script>
import { mapGetters } from 'vuex' // 從`vuex`庫中導入`mapGetters`函數,用于將getter映射到該組件的計算屬性中
import Logo from './Logo'
import SidebarItem from './SidebarItem'
import variables from '@/styles/variables.scss'export default {// 在該組件中注冊了`SidebarItem`和`Logo`兩個組件,以便在模板中使用它們components: { SidebarItem, Logo },// `computed`計算屬性中,可以定義一些依賴于其他數據的屬性。這些屬性的值會根據其依賴的數據動態計算得出,并在依賴數據發生變化時自動更新。// `computed`計算屬性的定義方式可以是一個對象,對象的每個屬性都是一個計算屬性的定義// `...mapGetters([...])`將`mapGetters`返回的映射對象展開并添加到該組件的計算屬性中,這樣可以直接訪問映射的getter// mapGetters([...])里的數組中包含想要映射的getter方法的名稱computed: {...mapGetters(['permission_routes','sidebar']),// 根據當前路由對象的元信息(`meta`)中的`activeMenu`屬性來確定活動的菜單項。// 如果未設置`activeMenu`屬性,則返回當前路徑(`path`)activeMenu() {const route = this.$route // `this.$route`是在Vue中訪問當前路由的對象(全局屬性,只讀,不能直接更改路由信息)const { meta, path } = route// if set path, the sidebar will highlight the path you setif (meta.activeMenu) {return meta.activeMenu // 側邊欄將高亮顯示設置的路徑}return path // 如果未設置`activeMenu`屬性,則返回當前路由的路徑。側邊欄將根據當前路徑高亮顯示相應的菜單項},showLogo() {return this.$store.state.settings.sidebarLogo},variables() {return variables},isCollapse() {// 如果`opened`屬性為`true`,則`isCollapse`為`false`,表示側邊欄未折疊;// 如果`opened`屬性為`false`,則`isCollapse`為`true`,表示側邊欄已折疊return !this.sidebar.opened}}
}
</script>
2.2 SidebarItem.vue
具體遍歷顯示每一個具體的菜單項。
<template><div v-if="!item.hidden" class="menu-wrapper"><!-- 這的item就是route,onlyOneChild就是當前route下的子菜單 --><!-- 1判斷route下是否為0或1個子菜單 && 2(!當前route下的子菜單是還存在子菜單||子菜單不存在時) && 3--><!-- 這里的template:當前route下只有1個或0個子菜單,且唯一子菜單下不存在下級菜單時,執行這段代碼效果:菜單欄中,該route為一級菜單,不顯示其子菜單--><template v-if="hasOneShowingChild(item.children,item) && (!onlyOneChild.children||onlyOneChild.noShowingChildren)&&!item.alwaysShow"><!-- 其子菜單中存在meta --><app-link v-if="onlyOneChild.meta" :to="resolvePath(onlyOneChild.path)"><el-menu-item :index="resolvePath(onlyOneChild.path)" :class="{'submenu-title-noDropdown':!isNest}"><item :icon="onlyOneChild.meta.icon||(item.meta&&item.meta.icon)" :title="onlyOneChild.meta.title" /></el-menu-item></app-link></template><!-- 存在多級子菜單的時候 --><el-submenu v-else ref="subMenu" :index="resolvePath(item.path)" popper-append-to-body><!-- 這里的插槽名為title;作用和上面一樣,主要是顯示一級菜單,但這里沒用app-link讓該菜單具有跳轉功能 --><template slot="title"><item v-if="item.meta" :icon="item.meta && item.meta.icon" :title="item.meta.title" /></template><!-- 具體的菜單項,遍歷各個子菜單 --><sidebar-itemv-for="child in item.children":key="child.path":is-nest="true":item="child":base-path="resolvePath(child.path)"class="nest-menu"/></el-submenu></div>
</template><script>
import path from 'path'
import { isExternal } from '@/utils/validate'
import Item from './Item'
import AppLink from './Link'
import FixiOSBug from './FixiOSBug'export default {name: 'SidebarItem',components: { Item, AppLink },// 通過 `mixins` 可以將一些常用的選項(如 `data`、`methods`、`created` 等)或復雜邏輯封裝成可復用的模塊,并在多個組件中混入使用mixins: [FixiOSBug],// 用于定義組件的屬性。可以是數組、對象或具體的屬性定義。通過 props 可以接收組件外部傳入的數據,并在組件內部使用props: {// route objectitem: {type: Object,required: true},isNest: {type: Boolean,default: false},basePath: {type: String,default: ''}},data() {// To fix https://github.com/PanJiaChen/vue-admin-template/issues/237// TODO: refactor with render function// 當前route的子菜單this.onlyOneChild = nullreturn {}},methods: {hasOneShowingChild(children = [], parent) {const showingChildren = children.filter(item => {if (item.hidden) {return false} else {// Temp set(will be used if only has one showing child)this.onlyOneChild = itemreturn true}})// 只存在一個子菜單// When there is only one child router, the child router is displayed by defaultif (showingChildren.length === 1) {return true}// 不存在菜單// Show parent if there are no child router to displayif (showingChildren.length === 0) {// 如果沒有子菜單顯示,將父級菜單的一些屬性復制到`onlyOneChild`對象中,同時設置`onlyOneChild`的`path`為空字符串,// 并設置`noShowingChildren`屬性為`true`,表示沒有子菜單顯示。最后返回`true`。this.onlyOneChild = { ... parent, path: '', noShowingChildren: true }return true}// 子菜單存在多個的時候return false},resolvePath(routePath) {// `isExternal(routePath)`函數判斷`routePath`是否為外部鏈接,如果是外部鏈接,則直接返回`routePath`,不做處理// 當只有唯一子菜單時,`routePath`是子菜單路徑if (isExternal(routePath)) {return routePath}// 當只有唯一子菜單時,`basePath`是父級菜單的路徑if (isExternal(this.basePath)) {return this.basePath}// `path.resolve()`函數將`this.basePath`和`routePath`拼接成一個完整的路徑,并返回該路徑// 返回 `/父級菜單的路徑/子菜單路徑`return path.resolve(this.basePath, routePath)}}
}
</script>
2.3 Link.vue
<template><!-- eslint-disable vue/require-component-is --><component v-bind="linkProps(to)"><slot /></component>
</template><script>
import { isExternal } from '@/utils/validate'export default {props: {to: {type: String,required: true}},methods: {linkProps(url) {if (isExternal(url)) {return {is: 'a', // 標簽名href: url, // 鏈接target: '_blank', // 用于指定鏈接在哪個窗口或框架中打開,`_blank`在新的標簽頁中打開鏈接rel: 'noopener' // 用于指定鏈接與當前頁面之間的關系,當使用`target="_blank"`時,防止新打開的窗口通過`window.opener`屬性訪問到當前頁面的信息,提高安全性。}}return {is: 'router-link', // 標簽名to: url}}}
}
</script>