需求:增加權限控制,實現不同角色顯示不同的路由導航
思路:每次登陸后請求接口返回當前角色路由
核心方法:vue-router2.2.0的addRoutes方法 + vuex
以下是我實現的獲取菜單路由的方法,我將該方法的調用放在首頁組件的生命鈎子中,即便用戶刷新瀏覽器清空了路由還是會重新調用接口獲取,不至於會丟失。同時考慮到會有切換用戶的可能,所以不將獲取到的路由信息保存到cookie或者localstorage當中
獲取菜單之前先判斷routerState,避免多次請求, 我這里使用element-ui的導航菜單功能v-for循環this.myRouter參數即可顯示動態路由導航
1 /** 2 * 獲取菜單 3 */ 4 getMenu () { 5 if (this.$store.getters.routerState === false) { 6 // 清理已經存在的動態路由 7 this.clearDynamicRoute() 8 // 更改請求路由狀態為true 9 this.$store.commit('SET_ROUTERSTATE', true) 10 getMyMenu().then((res) => { 11 if (res.code === '0') { 12 // 格式化路由,將數據轉為addRoutes可接受的route格式數組 13 let myMenu = this.formatMenu(res.data.menu) 14 if (myMenu.length <= 0) { // 沒有動態路由 15 return 16 } 17 for (let index = 0; index < myMenu.length; index++) { 18 // 將請求的路由先存放到options對象中 19 this.$router.options.routes.push(myMenu[index]) 20 } 21 // 將完整需要顯示的路由添加進去 22 this.$router.addRoutes(this.$router.options.routes) 23 // 這里將路由顯示在頁面上 24 this.MyRouter = this.$router.options.routes 25 } 26 // 在這里就可以打印出新路由 27 console.log(this.$router) 28 }) 29 } 30 }