Vue Router nested routing

Real life application interface, typically a combination of components nested together. Similarly, URL of each segment according to a certain structure dynamic path may also correspond to the layers of the nested components, for example:

/user/foo/profile                     /user/foo/posts
+------------------+                  +-----------------+
| User             |                  | User            |
| +--------------+ |                  | +-------------+ |
| | Profile      | |  +------------>  | | Posts       | |
| |              | |                  | |             | |
| +--------------+ |                  | +-------------+ |
+------------------+                  +-----------------+

With  vue-routerthe use of nested routing configuration, you can simply express this relationship.

Then the festival created app:

<div id="app"> <router-view></router-view> </div> 
const User = {
  template: '<div>User {{ $route.params.id }}</div>' } const router = new VueRouter({ routes: [ { path: '/user/:id', component: User } ] }) 

Here  <router-view> it is the top export, rendering components to match the most advanced routing. Similarly, a component can also be rendered themselves contain nested  <router-view>. For example, in  User adding a template component  <router-view>:

const User = {
  template: ` <div class="user"> <h2>User {{ $route.params.id }}</h2> <router-view></router-view> </div> ` } 

To render the components in a nested outlet, it is necessary  VueRouter to use the parameter  children configuration:

const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, children: [ { // 当 /user/:id/profile 匹配成功, // UserProfile 会被渲染在 User 的 <router-view> 中 path: 'profile', component: UserProfile }, { // 当 /user/:id/posts 匹配成功 // UserPosts 会被渲染在 User 的 <router-view> 中 path: 'posts', component: UserPosts } ] } ] }) 

Pay attention to  / the nested path it will be treated as the beginning of the root path. This allows you full use nested path components without having to set up nested.

You will find that children the configuration is like  routes the same configuration of routing configuration array, so, you can nest a multi-layer routing.

At this point, based on the above configuration, when you visit  /user/foo , the User export will not render anything, it is because there is no match to the appropriate sub-routes. If you want to render something, you can provide an empty sub-routes:

Guess you like

Origin www.cnblogs.com/zjhcap/p/11449337.html