需求:增長權限控制,實現不一樣角色顯示不一樣的路由導航vue
思路:每次登錄後請求接口返回當前角色路由vue-router
核心方法:vue-router2.2.0的addRoutes方法 + vuexvuex
如下是我實現的獲取菜單路由的方法,我將該方法的調用放在首頁組件的生命鉤子中,即使用戶刷新瀏覽器清空了路由仍是會從新調用接口獲取,不至於會丟失。同時考慮到會有切換用戶的可能,因此不將獲取到的路由信息保存到cookie或者localstorage當中element-ui
獲取菜單以前先判斷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 }