qq_27437991
无名万物
2018-09-08 12:33

Vue-router动态路由匹配到正常路由怎么办

5
  • vue.js
  • javascript

在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

如上,当访问/username时匹配/:id,但是之后的路由无论访问/user、/login等都是匹配的/:id这个路由。

求教该怎么写路由才能让匹配正确的路由?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答