Vue Router

1. Install

1.1 NPM install

npm i vue-router -S

Copy the code

1.2 introduced the Router

The project used is built from the single-file component article.

Single-file component [1]

Introduce router in man.js

import VueRouter from 'vue-router'

Vue.use(VueRouter)

Copy the code

1.3 use the router

  • Add it in the SRC folder
    • router/index.js
    • pages/a.vue
    • pages/b.vue
image-20200730150514499
  • Add the following information to a. ue and B. ue
<template>
  <div>pageA</div>
</template>
<script>
export default {
  name: 'vueA'
};
</script>
<style lang="less" scoped></style>
Copy the code
  • Add the following information to router/index.js
import VueRouter from 'vue-router';

import VueA from '.. /pages/a.vue';

import VueB from '.. /pages/b.vue';



/ / the route configuration

const routes = [

  {

    path'/a'.// the url matches the address

    name: 'pageA'.// route name

    component: VueA // Render the pricing

  },

  {

    path'/b'.

    name'pageB'.

    component: VueB

  }

];



// Create a Router instance

const router = new VueRouter({

  mode'hash'./ / hash routing

  base: process.env.BASE_URL,

  routes

});



/ / export the router

export default router;



Copy the code
  • App. Vue file
<template> <div id="app"> <div> -- Routing exit --> <! <router-view></router-view> </div> </template

<script> export default { name: 'App', components: {} }; </script>

Copy the code

  • The main js file
import Vue from 'vue';

import VueRouter from 'vue-router';

import router from './router';



Vue.use(VueRouter);



new Vue({

  router, // Inject the router at the root component so that all child components can get routing information from the vm.$router

  render: (h) = > h(App)

}).$mount('#app');



Copy the code

Inject the router, at the root component, so that all child components can get routing information through vm.$router

  • Open your browser and enter the project address:http://localhost:8081/#/
image-20200730161756598
  • Url Enter a. ue page address:http://localhost:8081/#/a
image-20200730161951042
  • Url Enter b. ue page address:http://localhost:8081/#/b
image-20200730162014736
  • Modify app.vue code
< the template > < div id = "app" > < div > home page < / div > < a - button @ click = "push ('/a / 1 ')" > a < / a - button > < a - button @click="push('/b/2')">b</a-button> <hr /> <! -- Routing exit --> <! <router-view></router-view> </div> </templateCopy the code

<script> export default { name: 'App', components: {}, methods:{ push(path){ this.$router.push(path) } } }; </script>

  • Modify the router. Js
/ / the route configuration

const routes = [

  {

    path'/a/:id'.// the url matches the address

    name: 'pageA'.// route name

    component: VueA // Render the pricing

  },

  {

    path'/b/:id'.

    name'pageB'.

    component: VueB

  }

];

Copy the code
  • Modify a. value and b. value
<template> <div>pageA</div> </template> <script> export default { name: 'vueA', mounted(){ console.log('this.$route.params: ', this.$route.params); }}; </script>Copy the code
  • View the page and click the button
image-20200730174556888
image-20200730174653125
  • Matching priority

Sometimes, the same path can match multiple routes. In this case, the priority of the matched routes is the highest according to the route definition order: the one defined first has the highest priority

2. Configure routes

The routing label

  • Router-link: indicates the label on the route page
  • Router-view: route page rendering area

Routing Configuration

  • path: string,
  • component? : Component,
  • name? : string, // Named route
  • components? : {[name: string]: Component}, // Name view components
  • redirect? : string | Location | Function,
  • props? : boolean | Object | Function,
  • alias? : string | Array<string>.
  • children? : Array<RouteConfig>, // Nested by
  • beforeEnter? : (to: Route, from: Route, next: Function) => void,
  • meta? : any,
  • caseSensitive? : Boolean, // is the matching rule case sensitive? (Default: false)
  • pathToRegexpOptions? : Object

Route Router build parameters

  • Routes: specifies the route configuration
  • Mode: indicates the router mode
  • Base: indicates the basic path of the router
  • LinkActiveClass: Indicates the class name of router-link activation
  • LinkExactActiveClass: Specifies the class name in router-link exact mode
  • ScrollBehavior: Displays the scrolling behavior of the route page

The sample

  • Label use
<template>

<! -- Configure the jump tag -->

  <router-link to="/a">A menu</router-link>

  <div>

  <! -- route route render location -->

    <router-view></router-view>

  </div>

</template> 



Copy the code
  • Routes configuration
import PageA from './pageA.vue'

import PageB from './pageB.vue'



/ / the route configuration

const routeA = {

  name:'a'.

  path:'/a'.

  components:PageA

}

const routeB = {

  name:'b'.

  path:'/b'.

  components:PageB

}



const routeRedirect = {

  name:'redirect'.

  path:The '*'.

  redirect:'/a' // routeA

}



// routes Configures the Array set of routes

const routes = [routeA,routeB,routeRedirect]



export default routes;

Copy the code
  • The Router configuration


import VueRouter from 'vue-router';

import routes from './routes';



const router = new VueRouter({

  routes:routes,

  mode:'hash'

  base:'/'.

  linkActiveClass:'classA'

  // ...

})



export default router



Copy the code

2.1 Router-link Forward link

The

component enables users to (click) navigate in applications with routing capabilities. The to attribute specifies the destination address, which is rendered as a
tag with the correct link by default. You can configure the tag attribute to generate additional tags. In addition, when the destination route is successfully activated, the link element automatically sets a CSS class name to indicate that the route is activated.


< p style = “max-width: 100%; clear: both;

  1. It behaves the same whether it’s HTML5 History mode or hash mode, so you don’t have to change anything when you switch routing modes or degrade using Hash mode in IE9.
  2. In HTML5 History mode, router-Link guards click events so that the browser does not reload the page.
  3. When you use the base option in HTML5 history mode, all to attributes don’t need to be written.
  • attribute
  1. to

A route destination can be a path string or a destination route object

  • Type: string | the Location

  • required

Represents a link to the destination route. When clicked, the internal value of to is immediately passed to router.push(), so this value can be a string or an object describing the destination location.

<! -- string -->

<router-link to="home">Home</router-link>

<! -- Render result -->

<a href="home">Home</a>



<! -- JS expression with v-bind -->

<router-link v-bind:to="'home'">Home</router-link>



<! -- No v-bind, just like any other attribute -->

<router-link :to="'home'">Home</router-link>



<! - ditto -- -- >

<router-link :to="{ path: 'home' }">Home</router-link>



<! -- Named route -->

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>



<! /register? plan=private -->

<router-link :to="{ path: 'register', query: { plan: 'private' }}"

  >
Register</router-link

>




Copy the code
  1. replace

Load the route in replace mode

  • Types: Boolean

  • Default value: false

With the replace attribute, when clicked, router.replace() is called instead of router.push(), so no history is left after navigation.

<router-link :to="{ path: '/abc'}" replace></router-link>

Copy the code
  1. append

Add the path to the end of the CURRENT URL

  • Types: Boolean

  • Default value: false

After the AppEnd property is set, the base path is added before the current (relative) path. For example, if we navigate from /a to a relative path B, the path is /b if append is not configured, and /a/b if configured

<router-link :to="{ path: 'relative/path'}" append></router-link>

Copy the code
  1. tag

Router-link render HTML tag, default is A

  • Type: string

  • Default value: “a”

Sometimes you want

to be rendered as some kind of tag, such as

  • . So we use the Tag Prop class to specify which tag, which again listens for clicks and triggers navigation.
  • <router-link to="/foo" tag="li">foo</router-link>

    <! -- Render result -->

    <li>foo</li>



    Copy the code
    1. active-class

    The name of the class class when activated

    • Type: string

    • Default value: “router-link-active”

    Sets the name of the CSS class to use when the link is activated. The default value can be configured globally with the route construction option linkActiveClass.

    1. exact

    Whether routes are accurately matched

    • Types: Boolean

    • Default value: false

    The default class name is activated or not based on the inclusion of a match. For example, if the current path starts with /a,

    will also be set to the CSS class name.


    ! To use exact matching mode for links, use the exact property:

    <! This link will only be activated if the address is / -->

    <router-link to="/" exact></router-link>

    Copy the code
    1. event

    [‘click’,’mouseEnter’…]

    • Type: string | Array < string >

    • Default: ‘click’

    Declares events that can be used to trigger navigation. It can be a string or an array containing strings.

    1. exact-active-class

    The class name of the exact match plan

    • Type: string

    • Default value: “router-link-exact-active”

    Configures the class that should be activated when a link is exactly matched. Note that default values can also be configured globally with the route constructor option linkExactActiveClass.

    1. aria-current-value
    • Type: ‘page’ | ‘step’ | ‘location’ | ‘date’ | ‘time’

    • Default value: “page”

    The value of ARIA-current configured when the link is activated according to an exact matching rule. This value should be ariA-current allowed in the ARIA specification. In most scenarios, the default value page should be the most appropriate.

    2.2 the router – the view

    The

    component is a functional component that renders the view component to which the path matches. A

    rendered component can also embed its own

    , depending on the nested path, rendering nested components.


    Other attributes (those not used by the router-View) are passed directly to the rendered component, and in many cases the data for each route is contained within the route parameters.

    Because it is also a component, it can be used with
    and

    . If both are used together, make sure to use

    on the inner layer:


    <transition>

      <keep-alive>

        <router-view></router-view>

      </keep-alive>

    </transition>

    Copy the code

    2.3 routes

    • routes

    • Type: Array < RouteConfig >

    RouteConfig type definition:

    interface RouteConfig = {

      path: string,

    component? : Component,

    name? : string,// Name the route

    components? : { [name: string]: Component },// Name the view component

    redirect? : string | Location |Function.

    props? : boolean |Object | Function.

    alias? : string |Array<string>,

    children? :Array<RouteConfig>, // Nested by

    beforeEnter? :(to: Route, from: Route, next: Function) = > void.

    meta? : any,



      / / server +

    caseSensitive? : boolean,// Is the matching rule case-sensitive? (Default: false)

    pathToRegexpOptions? :Object // Compile the re option

    }



    Copy the code
    1. path

    Page address path, data can be obtained through dynamic routing

    const routeA = {

      / / basic

      // path:'/a'

      // Dynamic path parameters start with a colon

      path:'/a:id'

    }

    Copy the code
    model Matching path $route.params
    /user user There is no
    /user/:username /user/evan { username: ‘evan’ }
    /user/:username/post/:post_id /user/evan/post/123 { username: ‘evan’, post_id: ‘123’ }
    1. component
    • Regular versus asynchronous components
    import VueA from '.. /pages/a.vue';



    / / the route configuration

    const routes = [

      {

        path'/a/:id'.// the url matches the address

        name: 'pageA'.// route name

        component: VueA / / component A

      },

      {

        path'/b/:id'.

        name'pageB'.

        // Asynchronous components that can be partitioned by Webpack automatic code

        component: (a)= > import(/* webpackChunkName: "group-foo" */ '.. /pages/b.vue')

      }

    ];

    Copy the code

    Route lazy loading [2]

    1. name
    • The name command is used to redirect routes

    To link to a named route, pass an object to router-link’s to property:

    <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

    Copy the code

    This is the same thing as code calling router.push() :

    router.push({ name'user'.params: { userId123 }})

    Copy the code

    Both methods navigate the route to the /user/123 path.

    Route naming [3]

    1. components
    • Named view

    Named View [4]

    1. redirect
    • redirect

    Redirect [5]

    1. props
    • Route component parameters are transmitted

    Routing Component Parameter Transmission [6]

    1. alias
    • The alias

    The alias [7]

    1. children
    • Embedded routines by

    Nested routines are determined by [8]

    1. beforeEnter
    • Route guard hook function

    Navigation Guard [9]

    1. meta
    • Routing meta information

    Routing meta information [10]

    1. caseSensitive
    • Whether the matching rule is case sensitive
    1. pathToRegexpOptions
    • Option to compile the re

    2.4 the Router

    1. routes

    The route of the Array

    1. mode

    Routing mode Hash or history

    • Type: string

    • Default value: “hash” (the browser environment) | “the abstract” (Node. Js environment)

    • Optional value: “hash” | | “history”, “abstract”

    1. base

    Base path of routing

    • Type: string

    • Default value: “/”

    The base path of the application. For example, if the entire single-page application service is under /app/, then base should be set to “/app/”.

    1. linkActiveClass
    • Type: string

    • Default value: “router-link-active”

    Global configuration

    Default active class. Refer to the router – the link.

    1. linkExactActiveClass
    • Type: string

    • Default value: “router-link-exact-active”

    Global configuration

    specifies the class that is precisely activated by default. You can browse router-link at the same time.

    1. scrollBehavior

    Route Scroll after entering the page

    • Type: the Function

    Vue Router API[11]

    Focus on not getting lost

    Reference

    [1]

    Single file components: https://fearlessma.github.io/FENotes/vue/vueBase/vue%E5%8D%95%E6%96%87%E4%BB%B6%E7%BB%84%E4%BB%B6.html


    [2]

    Route lazy loading: https://router.vuejs.org/zh/guide/advanced/lazy-loading.html#%E6%8A%8A%E7%BB%84%E4%BB%B6%E6%8C%89%E7%BB%84%E5%88%86%E5%9 D%97


    [3]

    Routing name: https://router.vuejs.org/zh/guide/essentials/named-routes.html


    [4]

    Named view: https://router.vuejs.org/zh/guide/essentials/named-views.html#%E5%B5%8C%E5%A5%97%E5%91%BD%E5%90%8D%E8%A7%86%E5%9B%BE


    [5]

    Redirect: https://router.vuejs.org/zh/guide/essentials/redirect-and-alias.html#%E9%87%8D%E5%AE%9A%E5%90%91


    [6]

    Routing component mass participation: https://router.vuejs.org/zh/guide/essentials/passing-props.html


    [7]

    Alias: https://router.vuejs.org/zh/guide/essentials/redirect-and-alias.html#%E5%88%AB%E5%90%8D


    [8]

    Embedded routines by: https://router.vuejs.org/zh/guide/essentials/nested-routes.html


    [9]

    Navigation guard: https://router.vuejs.org/zh/guide/advanced/navigation-guards.html


    [10]

    Routing meta information: https://router.vuejs.org/zh/guide/advanced/meta.html


    [11]

    Vue Router API: https://router.vuejs.org/zh/api/