Nested routing of vue-router


I. Introduction

Nested routing is a very common feature

  • For example, in the home page, we want to access some content through /home/news and /home/message.
  • One path maps one component, and accessing these two paths will also render two components separately.
    Insert picture description here

Second, use steps

There are two steps to implement nested routing:

  • Create the corresponding sub-components, and configure the corresponding sub-routes in the route map
  • The internal components used <router-view>labels

1. Create components corresponding to two sub-routes
Insert picture description here

2, to render nested assembly outlet, VueRouter required parameters in childrenthe configuration

The children configuration is an array just like the routes configuration, so you can also nest multiple layers of routes.

Note: in order to /nest at the beginning of the path will be used as the root path, the sub-routing without any increase /. When generating a route, the path on the main route will be automatically added before the sub-route, so the path on the sub-route does not need to redeclare the path on the main route.

//配置路由的信息
import Vue from 'vue'
import Router from 'vue-router'

//路由懒加载
const Home = () => import('../components/Home')
const HomeMessage = () => import('../components/HomeMessage')
const HomeNews = () => import('../components/HomeNews')

Vue.use(Router)

const routes = [
  {
    
    
    path:'',
    redirect:'/home'
  },
  {
    
    
    path: '/home',
    component: Home,
    children:[
      {
    
    
        path:'news', //嵌套路由的时候,路径前边不能加 /
        component:HomeNews
      },
      {
    
    
        path:'message',
        component: HomeMessage
      }
    ]
  }
]

const router = new Router({
    
    
  routes
});

export default router

3. Use in Home component

//Home.vue文件
<template>
  <div>
    <h2 class="title">我是首页Home</h2>
    //注意这里的路径必须是完整的
    <router-link to="/home/news">新闻</router-link>
    <router-link to="/home/message">消息</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
  export default {
    
    
    name: "Home"
  }
</script>

<style scoped>

</style>

At this point, based on the above configuration, when you visit /home, the router-view will not render anything, because there is no matching sub-route. If you want to render something, you can provide an empty sub-route

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/home', 
      component: Home,
      children: [
        // 当 /home 匹配成功,
        // HomeNews会被渲染在 Home的 <router-view> 中
        // { path:'', redirect:'news'},使用重定向
        {
    
     path: '', component: HomeNews},

        // ...其他子路由
      ]
    }
  ]
})

3. Information

Nested routing | Vue Router official website

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/112788901