<!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> 后台权限的管理需要用到动态添加路由, 管理员的权限不一样,展示的界面不一样,登录时判断身份,获取权限, 例如:超级管理员与用户管理人员
原文地址:https://www.cnblogs.com/bao2333/p/10255267.html
时间: 2024-11-07 22:17:33