Vue router nested route

Posted by walter8111 on Thu, 30 Apr 2020 22:26:49 +0200

1, Foundation


$ npm install vue  //Install vue
$ npm install vue-router //Install Vue router

Or quote < script >

<script src=""></script>
<script src=""></script>

I'm referring to script directly in HTML here


  • index.html
  • app.js
//index.html file
  <div id="app">
      <!-- Use router-link Components to navigate. -->
      <router-link to="/foo">home page</router-link>
      <router-link to="/bar">about</router-link>
      <router-link to="/user/Wang Ma">Wang Ma</router-link>
      <router-link to="/user/gossip" tag="li">gossip</router-link>
      <!-- Route exit -->
  <script src=""></script>
  <script src=""></script>
  <script src="app.js"></script>

Router link: it will be rendered as a < a > tag by default
To: attribute specifies the link. (corresponds to path)
Tag: modify the router link tag
router-view: route rendering

  1. Define (route) components.

const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const Bar1 = { template: '<div>My name is{{$}}</div>' }
//You can also import from other files
//$route.params parameter + name after

2. Define route

const routes = [
    { path: '/foo', component: Foo },
    { path: '/bar', component: Bar },
    { path: '/user/:name', component: Bar1 }
    // Dynamic path parameters start with a colon

path: address of the route (corresponding to to)
Component: component

  1. Create router instance, and then transfer it to routes configuration
// You can also pass other configuration parameters, but it's so simple first.
const router = new VueRouter({
    routes   // (abbreviation) equivalent to routes: routes
  1. Create and mount root instances.
// Remember to inject routes through router configuration parameters,
// So that the whole application has routing function
 new Vue({

2, Child route (nested route)

//Define components
const Bar1 = {
    template: `
            <div>My name is{{$}}</div> 
            //Router link of sub route 
            //append adds a base road before the current path (a more is appended to the current address)
            //Equivalent to / user/:name/more
            <router-link to = "more" append>More information</router-link> 
            <router-view></router-view> //Sub route rendering
const Bar2 = {
    template: `
    <div> User: {{$}}
         <p>{{$}}It's a whore</p>
//Define route
const routes = [{
        path: '/user/:name', component: Bar1,
      //children are used to nest routes, which can be nested in multiple layers.
        children: [{
            path: 'more',
            component: Bar2,

Child route.gif

This article references Official website

Topics: Vue npm Attribute