动态添加路由addRoutes
Posted bao2333
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态添加路由addRoutes相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body>
<div id="app"> <ul> <li v-if="!item.hidden" v-for="item in user" :key="item.path"> {{item.title}} </li> </ul> </div> </body> <script src="../js/vue.js"></script> <script src="../js/vue-router.js"></script> <script src="../js/vuex.js"></script> <script> const routes = [ { path: ‘/‘, //path就是对应导航的路径 title: ‘首页‘ //title就是对应的导航的名字 }, { path: ‘/page1‘, title: ‘分页1‘ }, { path: ‘/page2‘, title: ‘分页2‘ }, { path: ‘/page3‘, title: ‘分页3‘ }, { path: ‘/page4‘, title: ‘分页4‘ }, { path: ‘/login‘, title: ‘登录‘, hidden: true }, { path: ‘/404‘, title: ‘404‘, hidden: true //隐藏不需要渲染到页面上的路由 } ] const asyncUser = [ { path: ‘/page5‘, title: ‘分页5‘, meta: { roles: [‘admin‘] } }, { path: ‘/page6‘, title: ‘分页6‘, meta: { roles: [‘admin‘,‘guest‘] } } ]
//模拟一个登录用户 const user = { role: ‘guest‘ } const store = new Vuex.Store({ state: { user: null, routes }, mutations: { setRoutes (state, router) { state.routes = [...state.routes, ...router] }, setUser (state, user) { state.user = user } } }) const router = new VueRouter({ routes }) router.beforeEach((to, from, next) => {
//判断user信息是否已经获取 if (!store.state.user) {
//根据用户的类型来生成对应的新路由 const newRouter = asyncUser.filter(route => route.meta.roles.includes(user.role)) //将新路由添加到路由中
router.addRoutes(newRouter)
//为了正确渲染导航,将对应的新的路由添加到vuex中 store.commit(‘setRoutes‘, newRouter)
//将登录得到的use而添加到user中 store.commit(‘setUser‘, user) } }) const app = new Vue({ el: "#app", router, store, computed: { user () {
//获取到vuex中的routes用来渲染导航 return this.$store.state.routes } } }) </script> </html>
后台权限的管理需要用到动态添加路由, 管理员的权限不一样,展示的界面不一样,登录时判断身份,获取权限, 例如:超级管理员与用户管理人员
以上是关于动态添加路由addRoutes的主要内容,如果未能解决你的问题,请参考以下文章