无名万物 2018-09-08 12:33 采纳率: 0%
浏览 1613
已结题

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

在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条回答 默认 最新

  • devmiao 2018-09-08 15:51
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值