vue項目處理菜單權限
第一種:后臺直接返回菜單數(shù)據,例如:
menuList:[
{
path:'/home',
icon:'icon home',
title:'首頁'
},
{
path:'/table',
icon:'icon table',
title:'表單'
},
...
]
數(shù)據返回后,直接拿到el-menu中去遍歷(個人使用的elementUI)
<el-menu
:default-active="routh"
router
:collapse="isCollapse"
class="el-menu-vertical-demo"
:unique-opened="true"
>
<template v-for="(item, index) in menuList">
<template v-if="item.childMenuList">
<el-submenu :index="index + 'index'" :key="index">
<template slot="title">
<i :class="item.menuIcon" class="icon iconfont"></i>
<span>{{ item.menuName }}</span>
</template>
<el-menu-item
v-for="(it, d) in item.childMenuList"
:key="d"
:index="it.menuPath"
class="child_menu"
:class="{ long_font: it.menuName.length > 6 }"
>{{ it.menuName }}</el-menu-item
>
</el-submenu>
</template>
<template v-else>
<el-menu-item :index="item.path" :key="index" class="main-menus">
<i :class="item.menuIcon" class="icon iconfont"></i>
<span slot="title">{{ item.menuName }}</span>
</el-menu-item>
</template>
</template>
</el-menu>
關于權限問題,在不同登錄者的權限下,返回不同的菜單信息,不影響展示
注意:以上的數(shù)組僅做參考,具體按照后端返回數(shù)據處理,前提是數(shù)據格式跟示例類似
第二種:后端返回的數(shù)據格式與正常路由中的格式差距過大,例如:
[
{'admin':'shopDetail'},
{'admin':'home'},
{'user':'userInfo'},
{'aaa','bbb'}
...
]
類似這種,個人暫時的處理方案為以下幾個點:
先定義一個菜單數(shù)組menuList,menuList中寫入僅通過不同權限進入的所有頁面
在menuList中添加用戶返回的菜單數(shù)據的相關信息,可以用key:value的形式(假設返回的菜單數(shù)據為returnMenuList)
-
通過menuList與returnMenuList進行比較,得到最終展示到頁面上的菜單lastMenuList
//數(shù)據僅供參考,具體按照實際業(yè)務邏輯及后端返回數(shù)據為準 //假設只有三個頁面 const menuList=[ { path:'home', icon:'icon home', title:'首頁', menuName:'bbb', //后端返回的菜單對應首頁 }, { path:'one', icon:'icon one', title:'頁面1', menuName:'aaa', //后端返回的菜單對應頁面1 }, { path:'two', icon:'icon two', title:'頁面2', menuName:'abc', //后端返回的菜單對應頁面2 }, ] //后端返回的用戶菜單信息 let returnMenuList=[ {'aaa':'a'}, //a代表頁面1 {'bbb':'home'}, //b代表頁面首頁 ] //比較menuList 與 returnMenuList 得到lastMenuList //再將lastMenuList展示到頁面上注意:該方法不展示用戶沒有該權限的頁面,但是能通過路由進去,此時需要添加一個判斷
let map = new Map(Object.entries(returnMenuList)); let menus = menuList.filter(item => { if (map.has(item.menu)) { return item.menu } }) /**根據權限匹配輸入框路由是否有權限訪問 */ let some = menus.some((r) => { return r.path === this.routh //在created中添加 this.routh=this.$route.path }) if (!some) { this.$router.replace('/404') }
有更好的處理權限方法歡迎小伙伴留言哦~