原本我们的路由配置是在router/index.js里面配置如图
图中我们需要引入 import xx from '@/views/xx' 需要的页面都要这样引入
还有白名单的方法也可以简化
import VueRouter from 'vue-router'
import Vue from 'vue'
import Layout from '@/views/layout'
import Login from '@/views/login'
import Dashboard from '@/views/dashboard'
import Article from '@/views/article'
Vue.use(VueRouter)
//路由配置
const router = new VueRouter({
routes: [
{ path: '/login', component: Login },
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [
{ path: 'dashboard', component: Dashboard },
{ path: 'article', component: Article }
]
}
]
})
//白名单
const whiteList = ['/login']
router.beforeEach((to, next, from) => {
const token = store.state.user.token
if (token) {
next()
return
}
if (whiteList.includes(to.path)) {
next()
return
}
next('/login')
})
export default router
如图路由的便捷方式就不用在引入了,直接在后面用箭头函数写就可以了,这样还精简了我们的代码质量看着也很舒服!!!
import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//路由配置便捷方式
const routes = [
{ path: '/login', component: () => import('@/views/Login') },
{
// path: '/',
// redirect: '/deshoard',
path: '/',
redirect: '/deshoard',
component: () => import('@/views/Layout'),
children: [
// 子路由必须以路由展开 保证先渲染父路由 父路由的基础上展开子路由
// 子路由不以/开头被认为简写 那么就会主动拼接 父路由/
{ path: 'deshoard', component: () => import('@/views/Deshoard') },
{ path: 'article', component: () => import('@/views/Article') }
// { path: '/home/deshoard', component: () => import('@/views/Deshoard') },
// { path: '/home/article', component: () => import('@/views/Article') }
]
}
]
const router = new VueRouter({
routes
})
//白名单的便捷方式
const whiteList = ['/login']
router.beforeEach((to, fron, next) => {
if (store.state.user.token) return next()
if (whiteList.includes(to.path)) return next()
next('/login')
})
export default router