Vue Router 实现动态路由和常见问题及解决方法

2020-06-16 06:51:43易采站长站整理

利用全局前置守卫对路由信息进行判断

1-判断用户是否登录1.1-若未登录,跳转至登录页面1.2-若已经登录,判断是否已获取路由列表1.2.1-若未获取,从后端获取、解析并保存到

Vuex
中1.2.2-若已获取,跳转至目标页面

这里我没做太多考察,直接将取到数据存储到了

Vuex
中,在实际项目应用的过程中应考虑数据存储的安全性。

如何实现路由列表解析?

JSON
格式的路由信息解析为
JavaScript
列表对象;
利用列表对象的
filter
方法实现解析函数,通过
component
判断是否为布局组件;
若为布局组件,使用布局组件代替
component
字符串;
若为具体页面,使用
loadView
函数加载对应的具体页面;
利用 router.addRoutes 方法动态添加路由

这一步就很简单了,将解析好的路由列表通过

router.addRoutes
方法添加到
Router
实例中即可。

简单的实现代码


// router/index.js
import Vue from 'vue'
import store from '@/store'
import Router from 'vue-router'
import { getToken } from '@/lib/util'

Vue.use(Router)

// 定义静态路由
const staticRoutes = [
{
path: '/login',
name: 'login',
meta: {
title: '登录页面',
hideInMenu: true
},
component: () => import('@/view/login/login.vue')
},
{
path: '/401',
name: 'error_401',
meta: {
hideInMenu: true
},
component: () => import('@/view/error-page/401.vue')
},
{
path: '/500',
name: 'error_500',
meta: {
hideInMenu: true
},
component: () => import('@/view/error-page/500.vue')
}
]

// 定义登录页面名称(为了方便理解才定义的)
const LOGIN_PAGE_NAME = 'login'

// 实例化 Router 对象
const router = new Router({
staticRoutes,
mode: 'history'
})

// 定义全局前置守卫(里面有两个坑要注意)
router.beforeEach((to, from, next) => {
// 通过自定义方法获取用户 token 用来判断用户登录状态
const token = getToken()
if (!token && to.name !== LOGIN_PAGE_NAME) {
// 如果没有登录而且前往的页面不是登录页面,跳转到登录页
next({ name: LOGIN_PAGE_NAME })
} else if (!token && to.name === LOGIN_PAGE_NAME) {
// 如果没有登录而且前往的页面是登录页面,跳转到登录页面