嵌套路由

// router.js
routes: [
    {
      path: "/dongtai",
      component: DongTai
      children: [
        {
          path: "news",
          component: DongTaiNew
        },
        {
          path: "about",
          component: DongTaiObout
        }
      ]
    }
  ]
  // index.vue
  <router-link to="/dongtai/news">新闻</router-link>
	<router-link to="/dongtai/about">关于</router-link>
  <router-view />
  // 如果?我想页面一打开就显示其中一个子路由,比如新闻路由
  {
      path: "/dongtai",
      // component: DongTai
      component: DongTai,
      children: [
        {
          path: "",// 这里表示的就是当前父级路由
          component: DongTaiNew
        },
        {
          path: "news",
          component: DongTaiNew
        },
        {
          path: "about",
          component: DongTaiObout
        }
      ]
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

解读

嵌套路由和动态理由的区别在于,动态路由是不用写死子路由的,实际上动态路由也是匹配子路由的一种,但是嵌套路由是需要写死子路由地址的,在 children 里; 一般用在面包屑导航那种的路由结构里,还有一些应用的路由数据是后端给的,那么嵌套的时候很多,就需要我们对嵌套有一个深层的了解

嵌套路由配合动态路由

// 这里需要注意children里的地址一定要写全。
const router = new VueRouter({
  routes: [
    {
      path: "/dongtai/:id",
      component: DongTai,
      children: [
        {
          path: "/dongtai/news",
          component: DongTaiNew
        },
        {
          path: "/dongtai/about",
          component: DongTaiObout
        }
      ]
    }
  ]
});
// 你会发现页面跳转到/dongtai里的时候空白页了,是的,没错,因为这还是动态路由,它需要/dongtai/xx 的形式,所以匹配不上,需要在它的上面写一个普通匹配
const router = new VueRouter({
  routes: [
    {
      path: "/dongtai",
      component: DongTai
    },
    {
      path: "/user/:id",
      component: User,
      children: [
        {
          path: "/dongtai/news",
          component: DongTaiNew
        },
        {
          path: "/dongtai/about",
          component: DongTaiObout
        }
      ]
    }
  ]
});
// 算是一个小坑吧,当初我看官网的时候的确脑子没转过来,卡了一会儿
// 贴出我的html部分
<router-link to="/dongtai/news">新闻</router-link>
<router-link to="/dongtai/about">关于</router-link>
<router-view />// 这里就是渲染出子路由的位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Last Updated:
Contributors: websong