1. 程式人生 > >動態添加路由addRoutes

動態添加路由addRoutes

com spa r.js 一個 put state round from role

<!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