Vue動態路由配置
技術選型:
- vue
- vuex
- vuex-persistedstate(vuex持久化)
- vue-router
直接上代碼
配置基本路由表:這部分路由為前端定死的路由,動態部分為home路由組件下的子路由
const routes = [ { path: '/home', name: 'home', component: Home, children: [] }, { path: '/login', name: 'Login', component: Login } ]
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
let router = new VueRouter({
routes,
});
兩種方式去添加動態路由,一種是在登錄后查詢路由表保存到vuex或者localStore下,然后通過前置守衛來動態的添加路由,另一種就是登陸之后使用$router.addRoute直接添加路由,后者並不推薦,因為再刷新頁面的時候會出現無法找到頁面的情況
這里介紹第一種方式:
/** * 前置守衛 */ router.beforeResolve((to, from, next) => { if (!hasRoute(to)) { addRoute(); next(to.fullPath) } else { next() } })
不難看出其中addRoute()為添加路由的方法,而hasRoute()方法是驗證當前路由對象中是否存在將要跳轉的路由,如果不存在添加,否則放行。這個判斷是必要的,如果沒有判斷,頁面將會無限重定向。而且只能寫成上訴格式,判斷成立next(to.fullPath),不成立next().
/** * 判斷當前路由是否存在 * @param to * @returns {boolean} */ function hasRoute(to) { let find = router.getRoutes().find(item => item.name === to.name); return !!find; }
代碼並不復雜,只是在當前路由表中查詢傳入的路由返回即可,存在返回true,否者false
/** * 添加路由 */ function addRoute() { let routeLocal = store.state.routes; routeLocal.forEach(item => { ("home", { path: item.path, component: (resolve) => resolve(require(`@/${item.component}`)), name: item.name }) }) }
首先在store中獲取路由信息,然后循環添加,當然也可以將路由信息存在cookie,localStore中。
將路由存在store中有一點問題,就是在刷新頁面的時候store同樣重置,這樣路由信息就沒有的,這里我采用vuex-persistedstate將vuex持久化,當然也可以在store中不存在路由時向后端請求查詢(有一個問題就是需要保證查詢是一個同步的,否則是不能被添加到路由對象中的),
也許有人會問 為啥添加路由不用router.addRoutes()呢?請看下圖
以下是vuex的配置:
import Vue from 'vue' import Vuex from 'vuex' import createPersistedState from "vuex-persistedstate" Vue.use(Vuex) export default new Vuex.Store({ state: { routes: null }, getters: { // getRouter: (state => { // state.routes.find() // }) }, mutations: { routesMutation(state, payload) { state.routes = payload; } }, actions: { routesActions(context, data) { context.commit("routesMutation", data) } }, plugins: [createPersistedState()] })
歡迎吐槽