Trouble of router view in Vue router

Posted by deeessay on Fri, 01 Nov 2019 20:33:35 +0100

When I first contacted vue, I was puzzled by the rendering of router view for a long time. I don't know why there are many router links and different router views, but why is there no confusion in rendering?

This is a demo I wrote myself

On the left is the primary route, on the right is the component corresponding to the primary route. On the right is the first component containing the secondary route.

 routes: [
    {
      path: '/',
      name: 'first',
      component: first
    },{
      path: '/first',
      name: 'first',
      component: first,
      children:[{
        path:'/one',
        name:'one',
        component:one
      },{
        path:'/two',
        name:'two',
        component:two
      },{
        path:'/three',
        name:'three',
        component:three
      }]
    }

The above is the routing configuration, where first corresponds to a router view.

<template>
  <div id="app">
    <sidebar />
    <router-view/>
  </div>
</template>

The sub route under first corresponds to a router view

<template>
<div id="content">
    <div>This is the first workspace</div>
    <router-link to="/one">first-one</router-link><br>
    <router-link  to="/two">first-two</router-link><br>
    <router-link to="/three">first-three</router-link>
    <router-view></router-view>
</div>
</template>

 

In this way, there are two router views in the page, but there will be no confusion in rendering. The reason is that the routing level is different and the components are different. When rendering, it is done at the same level.

When there are no multiple router views in the same level, there will be no rendering confusion, but when there are multiple router views in the same level, there will be confusion. The solution is to use named views.

<div id="app">
    <sidebar />
    <router-view name="a"></router-view>
    <router-view name="b"></router-view>
  </div>

In the routing configuration, set the components displayed in the corresponding router view under the corresponding path.

 routes: [
    {
      path: '/',
      name: 'first',
      components: {
        b: third,
        a: second
      }
    }

The first and second views in the root directory set now show the second and third components respectively.

Topics: PHP Vue