The official document: router.vuejs.org/zh/installa…

I. Routing Rules (Basic)

The so-called front-end routing is to change the URL, but the page does not refresh the whole. There are two main ways to achieve this

1. The URL hash

The hash of the URL is the anchor point (#), which essentially changes the href property of window.location. You can change the href by directly assigning location.hash, but the page does not refresh

Test directly on the browser command line:

> location.href
"http://localhost:8080"
> location.hash='/foo'
"/foo"
> location.href
"http://localhost:8080/#/foo"
Copy the code

Looking at Network, you can see that the page has not been refreshed

2. HTML5 history mode

The History interface is a new addition to HTML5 and has five modes to change the URL without refreshing the page

  1. history.pushState(data: any, title: string, url? : string | null) can be understood as a stack, to press the new url into the stack, the browser’s address bar display only the url on the top of the stack

    > location.href
    "http://localhost:8080/"
    > history.pushState({},' '."/app")
    undefined
    > location.href
    "http://localhost:8080/app"
    Copy the code
  2. history.replaceState(data: any, title: string, url? : string | null) does not retain the current url, direct replacement.

  3. history.go(delta? : number) pass in a number, a positive number to jump forward, a negative number to jump back,

    > location.href
    "http://localhost:8080/"
    > history.pushState({},' '."/app")
    undefined
    > location.href
    "http://localhost:8080/app"
    > history.replaceState({},' '.'/demo')
    undefined
    > location.href
    "http://localhost:8080/demo"
    > history.go(-1)
    undefined
    > location.href
    "http://localhost:8080/"
    Copy the code
  4. History.back () is equivalent to: history.go(-1)

  5. History.forward () is equivalent to: history.go(1)

Install and use vue-Router

1. Install

A Router can be added directly when creating a project using scaffolding, or by using the following command:

npm install vue-router --save
Copy the code

2. How to use vuE-Router:

General steps:

  1. Import the routing object and call vue.use (VueRouter)
  2. Create a route instance and pass in the route mapping configuration
  3. Mount the created route instance in the Vue instance

Example:

  • SRC /router/index.js: The general router configuration information is stored in SRC /router/index.js

    import Vue from "vue"
    // 1. Import VueRouter
    import VueRouter from "vue-router";
    
    // 2. Install the plugin using vue.use (VueRouter)
    Vue.use(VueRouter);
    
    // 3. Create the VueRouter object and configure the mapping
    const router = new VueRouter({
      // Configure the application relationship between routes and components
      routes: []})// 4. Pass the Router object to the Vue instance
    export default router;
    Copy the code
  • In the main. Js

    import Vue from 'vue'
    import App from './App.vue'
    // 5. Import. If you import a folder, the index.js file in the folder will be found automatically
    import router from "./router";
    
    Vue.config.productionTip = false
    
    new Vue({
      Mount the created route instance
      router,
      render: h= > h(App),
    }).$mount('#app')
    Copy the code

3. Route and component mapping

const router = new VueRouter({
  // Configure the application relationship between routes and components
  routes: [{// The default path of the route (specify which route to select when the page is first entered)
      path: '/'.redirect: '/home'
    },
    {
      path: '/home'.component: () = > import(".. /components/Home")}, {path: '/about'.component: () = > import(".. /components/About")}]})Copy the code

4. Using routes (router-link and router-view labels)

The

and

tags are both built-in components of vue-Router.


  • : used to change the address in the address bar

    • To: specifies the path. The default is the anchor point.

    • tag: The tag specifies what component to render after the

      is rendered. By default, it is rendered as a
      tag

    • Replace: This argument does not leave a history record, so specifying replace does not return the back key to the previous page

      (As you can imagine, the default underlying use of history.pushState() isto change the URL. Add replace and use history.replacestate () to change the URL.)

    • Active-class: When the routes corresponding to

      are successfully matched, a router-link-active class is automatically set for the current element. You can change the default class name by setting active-class. (See Chapter 3, Section 2 for all changes)


  • : This tag dynamically renders different components based on the current path.

    The rest of the page, such as the title/navigation at the top, or some copyright information at the bottom, is on the same level as

    . During route switchover, the components mounted by

    are switched, and other contents remain unchanged.

    • key: Identifies the current component. By default, == Route == is used. If there are parameters in the route, the full path can be used. (See 8/1 for details)
<template>
  <div id="app">
    <router-link to="/home">Home page</router-link>
    <router-link to="/about" tag="li" replace>about</router-link>

    <router-view></router-view>
	<! -- Use full path as identifier -->
	<router-view :key="$route.fullPath"></router-view>
  </div>
</template>
Copy the code

5. Using routes in events ($router)

Instead of using

, you can use another tag, such as a button, and then bind an event to change the URL:

<! -- The difference between push and replace is whether there is a history record -->
<button @click="$router.push('/home')">Home</button>
<button @click="$router.replace('/about')">About</button>
Copy the code

Vue uses this to access the $router property

export default {
  name: 'App'.method: {clickFunc() {
      this.$router.replace("/home"); }}}Copy the code
  • == Note == : Do not usehistory.pushState()history.replaceState()To modify the URL directly, which will bypassvue-router.

Other configuration when creating the VueRouter object

1. Mode (specify routing mode)

By default, path changes use the HASH of the URL. When creating the VueRouter object, change the mode property and set the routing mode to HTML5 History mode

const router = new VueRouter({
  // Configure the application relationship between routes and components
  routes: [].// Specify the routing mode
  mode: 'history'
})
Copy the code

2. LinkActiveClass (add class when route match is successful)

When the routes corresponding to

are successfully matched, a router-link-active class is automatically set for the current element.

This class is typically used for highlighted navigation menus or the bottom tabbar. However, the default router-link-active is used instead of modifying the class properties

You can also use linkActiveClass to modify this default class.

const router = new VueRouter({
  // Configure the application relationship between routes and components
  routes: [].// Specify the routing mode
  linkActiveClass: "active"
})
Copy the code

$route = $route

1. Dynamic routing (type of Params)

To pass an ID to the User component, we can do this by using the “Dynamic segment” in the vue-Router’s routing path. The “segment” is marked with a colon:. When a route is matched, the parameter value is set to this.$route.params $route

  • $route: Indicates the route that is currently active. That is, the corresponding route object in the Routes array

    $route is an object in the VueRouter array of these routers, and $route is an object in the VueRouter array of these routers. $route. routes[0] is $route if the route is active

  1. Add an idProp parameter to the path of the Vue-Router mapping to receive the id passed in. This parameter will be stored in$route.idProp
const router = new VueRouter({
  // Configure the application relationship between routes and components
  routes: [{path: '/user/:idProp'.component: () = > import(".. /components/User")},mode: 'history'
})
Copy the code
  1. The id parameter of the user added to the URL:
<! -- Router-link -->
<router-link :to="'/user/' + id" tag="button">The user</router-link>

<!-- 使用 JavsScript 的方式 -->
<button @click="$router.push('/user/' + id)">The user</button>
Copy the code
  1. use$route.paramsGets the passed idProp parameter
<template>
  <div>
    <h3>{{$route.params.idprop}} {{$route.params.idprop}}</h3>
    <li>This is the id obtained from the method: {{id2}}</li>
  </div>
</template>

<script>
  export default {
    name: "User".computed: {
      id2() {
        return this.$route.params.idProp; }}}</script>
Copy the code

2. Query type

Configure routing format: /router, that is, the common configuration transfer mode: directly pass the object, the object uses path to specify the route, and the query object to pass the path formed after passing the parameter: /router? Id = 123, / router? id=abc

  1. == Pass parameter == : Pass an object directly. The path of the object is used to specify the route and the query is used to specify the parameters

    <! -- Router-link -->
    <! - request address: http://localhost:8080/profile? Name = % E6%9 E5 8 e d % % % 9 9 b & b % age = 24 & heigth = 1.88 - >
    <router-link :to="{path: '/ profile, query: {name:' zhang 'age: 34}}">Zhang SAN file</router-link>
    
    <!-- 使用 JavsScript 的方式 -->
    <button @click="$router. Push ({path: '/ profile, query: {name:" bill ", the age: 24, heigth: 1.88}})">Li si file</button>
    Copy the code
  2. == Receive parameter == : profile. vue uses $route.query to get the incoming Query

    <template>
      <div>
        <li v-for="(val, key) in $route.query">{{key}}: {{val}}</li>
      </div>
    </template>
    Copy the code

Extension:

  • The full path of the URL, which explains why query is used for the literal argument above:
scheme:[//[user:password@]host[:port]][/]path[?query][#fragment] 
Copy the code

Five, set routine by

Embedding is a common feature, for example in a home page where we want to access some content via /home/news or /home/message. A path maps a component, and accessing the two paths also renders the two components separately. For example, when accessing /home/news, the home component is rendered before the news component is rendered within the home component.

The relationship between paths and components is as follows:

There are two main steps to realize the embedded routine:

  1. Create the corresponding child component and map it in the routechildrenTo configure the corresponding child route.
export default new VueRouter({
  // Configure the application relationship between routes and components
  routes: [{path: '/home'.component: () = > import(".. /components/Home"),
      children:[
        {
          path: ' '.redirect: 'news'
        },
        {
          // Note that/before the path, add to indicate the absolute path, not add to indicate the relative path
          // The following configuration matches the path /home/news
          path: 'news'.component: () = > import(".. /components/HomeNews")}, {path: 'messages'.component: () = > import(".. /components/HomeMessages")}]}]})Copy the code
  1. Used within a component<router-view>The label.
<template>
  <div>
    <h2>I am Home</h2>
    <p>I am the contents of Home</p>

    <button @click="$router.replace('/home/news')">Front page news</button>
    <button @click="$router.replace('/home/messages')">Front page news</button>
    <router-view></router-view>
  </div>
</template>
Copy the code

Vi. Navigation guards

The vue-Router provides navigation guards that listen for incoming and outgoing routes. The official website of navigation guard also said more clearly, this piece of direct see the official website is good (official website: poke here)

Here is an example of the global guard, other uses are similar.

Global front guard

Vue-router provides beforeEach and afterEach global hook functions that fire before and after route changes.

Register a global front guard with router.beforeeach:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) = > {
  // ...
  next();
})
Copy the code

When a navigation fires, the global front guard is called in the order it was created. The guard is being resolved asynchronously, where the navigation waits until all the guards have resolved.

Each guard method takes three arguments:

  • To: Route: indicates the destination Route object to be entered

  • From: Route: Indicates the Route that the current navigation is leaving

  • Next: Function: == Make sure to call this method to resolve the hook ==. The execution effect depends on the call parameters to the next method.

    • Next (): Makes the next hook in the pipeline. If all hooks have been executed, the state of the navigation is confirmed.

    • Next (false): Interrupt the current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL will be reset to the address of the FROM route.

    • Next (‘/’) or next({path: ‘/’}): jumps to a different address. The current navigation is interrupted and a new navigation is made. You can pass any location object to next and allow options such as replace: true, name: ‘home’ and any options used in the Router-link’s to prop or router-. push.

    • Next (error): (2.4.0+) If the argument passed to next is an error instance, the navigation will be terminated and the error will be passed to the registered callback of router.onError().

  • Here’s a small example:

    const router = new VueRouter({
      routes: [{path: '/home'.component: () = > import(".. /components/Home"),
          // Use the meta attribute to add data
          meta: {
            title: 'home'}}, {path: '/about'.component: () = > import(".. /components/About"),
          meta: {
            title: 'about'}}],mode: 'history'
    })
    
    router.beforeEach((to, from, next) = > {
      // Modify the header when the route is changed
      document.title = to.meta.title;
    
      // if subcomponents are matched, select meta as :(to. Matched is an array containing all subcomponents)
      document.title = to.matched[0].meta.title;
      next();
    });
    Copy the code

7. Routes are loaded lazily

When you package to build an application, the JavaScript package can become so large that it affects the page load.

The main function of lazy route loading is to package the corresponding components of the route into a js code block. The component is loaded only when the route is accessed.

The combination of Vue’s asynchronous components and Webpack’s code splitting capabilities makes it easy to lazy load routing components.

const router = new VueRouter({
  // Configure the application relationship between routes and components
  routes: [{path: '/home'.// The following is the lazy route loading method
      component: () = > import(".. /components/Home")}, {path: '/about'.component: () = > import(".. /components/About")}]})Copy the code

Eight, encountered problems

1. Multiple routes share the same component and interfere with each other

  • Problem description: a component has to display different data depending on the parameters passed in, while the state of the component remains (

    ). The problem is that when data in one component changes, data in other components changes as well.

  • The solution:

    <router-view :key="$route.fullPath"/>
    Copy the code