Vue动态路由配置-router.addRoute

Vue动态路由配置

技术选型:

  1. vue
  2. vuex
  3. vuex-persistedstate(vuex持久化)
  4. 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()]
})

欢迎吐槽

原文地址:https://www.cnblogs.com/Tiandaochouqin1/p/14677546.html