在router.js中定义了这样两个路径/:id、/user,因为动态路由是在根路径下
且先定义的,所以后面的路径不会匹配,访问任何路径会匹配到/:id这个路径下,具体代码如下:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
component: () => import('./views/index/Index.vue'),
children: [
{
path: '/',
redirect: {
name: 'index'
}
},
{
path: '/index',
name: 'index',
component: () => import('./views/pages/Home.vue')
},
{
path: ':user_name',
component: () => import('./views/index/Index.vue'),
children: [
{
path: '/',
name: 'user_info',
component: ()=>import('./views/pages/UserInfo.vue')
},
{
path: 'article',
name: 'user_article',
component: ()=>import('./views/pages/UserArticle.vue')
}
]
}
]
},
{
path: '/user',
component: () => import('./views/users/User.vue'),
children: [
{
path: '',
redirect: {
name: 'profile'
}
},
{
path: 'profile',
name: 'profile',
component: () => import('./components/user/Profile.vue')
},
{
path: 'editor',
name: 'editor',
component: () => import('./components/user/Editor.vue')
}
]
},
{
path: '/login',
name: 'login',
component: () => import('./views/Login.vue')
},
{
path: '/404',
name: '404',
component: () => import('./views/404.vue')
},
{
path: 'register',
name: 'register',
component: () => import('./views/Register.vue')
}
]
})
// router全局钩子函数
router.beforeEach((to, from, next) => {
NProgress.start()
if (to.path === '/login') {
next()
NProgress.done();
} else {
if (to.meta.requiresAuth && !getToken()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
NProgress.done();
} else {
next()
NProgress.done()
}
}
})
export default router