Vue Router is an official plug-in for vue.js, which is used to quickly implement single-page applications.

A single page application

SPA (Single Page Application) is a Single Page Application.

Single page, meaning that “all” of a site’s functionality is presented on a single page.

Representative back-end management system, mobile terminal, small programs, etc.

Advantages:

  • The development efficiency is improved by separating the front and back ends.
  • The structure is partially updated during service scenario switchover.
  • Good user experience, closer to native application.

Disadvantages:

  • Bad for SEO.
  • The first screen loading speed is slow.
  • The page complexity is high.

The front-end routing

Front-end routing refers to the mapping between URLS and content.

Prerequisites for configuring front-end routes include URL, content, and mapping.

For example, the mapping relationship between each content of a single page and a URL is front-end routing.

There are two ways to set front-end routes:

  • Hash way
  • The History way

Hash way

Using the hashchange event to monitor hash changes and update web content is the hash mode for setting front-end routes.

Hash is the part of a URL that represents the symbol # and is commonly used as an anchor point to jump around the page. When you click on various sections of the article’s table of contents as you read this article, you will notice that the URL in the address bar changes. This feature, which does not cause a whole page jump, is good for front-end routing.

<div>
  <a href="# /">Home page</a>
  <a href="#/category">Category pages</a>
  <a href="#/user">The user page</a>
</div>
<div id="container">This is the home page feature</div>
<script>
  // Prepare an object to encapsulate the hash function.
  var router = {
    // Route store location: stores the mapping between url and content handler
    routes: {},
    // Define the method of routing rules
    route: function (path, callback) {
      this.routes[path] = callback;
    },
    // Initializes the route
    init: function () {
      var that = this;
      window.onhashchange = function () {
        When the hash changes, we need to get the current new hash
        var hash = location.hash.replace(The '#'.' ');
        // Trigger the corresponding callback in routes based on the hashthat.routes[hash] && that.routes[hash](); }; }};var container = document.getElementById('container');
  // Define routing rules
  router.route('/'.function () {
    container.innerHTML = 'This is the home page function';
  });
  router.route('/category'.function () {
    container.innerHTML = 'This is the classification function.';
  });
  router.route('/user'.function () {
    container.innerHTML = 'This is a user function';
  });
  // Initialize the route
  router.init();
</script>
Copy the code

Summary of features:

  • Hash mode is compatible
  • The address has#Notation, not pretty
  • The forward and backward functions are cumbersome

To solve the problem of ugly addresses and forward and backward addresses, you can use another front-end routing method, History mode.

The History way

The History method uses the new functionality provided by HTML5 to realize front-end routing.

The history.pushState() command is used to change the URL and perform the action.

The forward and backward function first needs to save the routing flag when changing the URL. Listen for forward and back button actions through the PopState event and detect state. Call the initialization method to listen for forward and backward operations and process them.

<div>
  <a href="/">Home page</a>
  <a href="/category">classification</a>
  <a href="/user">The user</a>
</div>
<div id="container">This is the home page feature</div>
<script>
  var router = {
    // The object that stores the route
    routes: {},
    // Define the routing method
    route (path, callback) {
      this.routes[path] = callback;
    },
    // Used to trigger the specified routing operation
    go (path) {
      / / change the url
      history.pushState({ path: path }, null, path);
      // Triggers the route callback function
      this.routes[path] && this.routes[path]();
    },
    // Set the initialization method to check the function of the forward and back buttons
    init () {
      var that = this;
      window.addEventListener('popstate'.function (e) {
        var path = e.state ? e.state.path : '/'; that.routes[path] && that.routes[path](); }); }}; router.init();// Set the function of the a tag
  var links = document.querySelectorAll('a');
  var container = document.querySelector('#container');
  links.forEach(function (ele) {
    ele.addEventListener('click'.function (event) {
      router.go(this.getAttribute('href'));
      event.preventDefault();
    });
  });
  // Routing rules
  router.route('/'.function () {
    container.innerHTML = 'Home Page Features';
  });
  router.route('/category'.function () {
    container.innerHTML = 'Classification function';
  });
  router.route('/user'.function () {
    container.innerHTML = 'User features';
  });
</script>
Copy the code

Advantages:

  • The address format is nicer than the hash method
  • It is convenient to move forward and backward

Disadvantages:

  • Because it’s HTML5, compatibility is a bit poor
  • The backend must cooperate with the refresh process to prevent the path from being accessed

Vue Router using

Vue Router is the official route manager for vue.js, making it a piece of work to build single-page applications.

The official documentation

The basic use

The installation

Method 1: Download/CDN directly

  • Latest version:https://unpkg.com/vue-router/dist/vue-router.js
  • Specified version:https://unpkg.com/[email protected]/dist/vue-router.js

Mode 2. NPM mode

npm install vue-router
Copy the code

The introduction of

<! Vue router. Js is a plug-in for vue. Js.
<script src="lib/vue.js"></script>
<script src="lib/vue-router.js"></script>
Copy the code

use

<div id="app">
  <! -- Set the component used for routing operations -->
  <router-link to="/">Home page</router-link>
  <router-link to="/user">The user</router-link>
  <router-link to="/category">classification</router-link>
  <! -- Route display area -->
  <router-view></router-view>
</div>
<! Vue router. Js is a plug-in for vue. Js.
<script src="lib/vue.js"></script>
<script src="lib/vue-router.js"></script>
<script>
  // Define the component
  var Index = {
    template: '
       
Home page function
'
}; var User = { template: '
User function
'
}; var Category = { template: '
classification function
'
}; // Define routing rules var routes = [ { path: '/'.component: Index }, { path: '/user'.component: User }, { path: '/category'.component: Category } ]; // Create a Vue Router instance var router = new VueRouter({ routes }); // Create a Vue instance and inject the router var vm = new Vue({ el: '#app'.// router });
</script> Copy the code

Named view

If, after navigation, you want to display multiple views (components) at the same level, you need to name the view.

<div id="app">
  <router-link to="/">Home page</router-link>
  <router-link to="/user">The user</router-link>
  <router-view name="sidebar"></router-view>
  <! -- router-view default router-view default-->
  <router-view></router-view>
</div>
Copy the code

You need to set this parameter in the routing rule

// Define routing rules
var routes = [
  {
    path: '/'.components: {
      // Router-view name: component configuration object
      default: Index,
      sidebar: SideBar1
    }
  },
  {
    path: '/user'.components: {
      default: User,
      sidebar: SideBar2
    }
  }
];
Copy the code

Dynamic routing

When we need to map a certain type of URL to the same component, we need to use dynamic routing.

When defining routing rules, mark a part of a path with: to set it as a dynamic route.

// Set routing rules
var routes = [
  { 
    // indicates that '/user/1', '/user/2', and '/user/3' all point to this route
    path: '/user/:id'.component: User
  }
];
Copy the code

The information corresponding to the: part is called path parameters and is stored in vm.$route.params.

// Set the component
var User = {
  template: '
      
this is the function of user {{$route.params.id}}
}; Copy the code

Listening route parameter

To respond to route parameter changes, watch can listen for $route.

// Set the component
var User = {
  template: '
      
This is the function of user {{$route.params.id}}
'
.watch: { $route (route) { // console.log(route); console.log(route.params.id) } } }; Copy the code

Routing and the cords

The data can be received via $route.params, but this results in a high degree of coupling between the component and the data, which is difficult to handle if the component is reused elsewhere, using a parent component, or another component to pass the data.

We need to set the data through the props of the route and receive the data through the props of the component.

// Set routing rules
var routes = [
  {
    path: '/user/:id'.component: User
  },
  {
    path: '/category/:id'
    component: Category,
    props: true}];Copy the code

Define the components

var User = {
  template: This is the user {{$route.params.id}} function 
};
var Category = {
  props: ['id'].template: This is the classification {{id}} function  '
};
Copy the code

When there are multiple named views, you need to set the props of the route as the object.

// Set routing rules
var routes = [
  {
    path: '/user/:id'.component: User
  },
  {
    path: '/category/:id'.components: {
      default: Category,
      sidebar: SideBar,
      sidebar2: SideBar2
    },
    props: {
      default: true.sidebar: false.sidebar2: {
        // If you want to set static data, set an option corresponding to a component in props as an object,
        // The inner property is bound to the props of the component.
        a: State of '1'.b: '2'}}}];Copy the code

Embedded routines by

In actual scenarios, routes are usually composed of multi-layer nested components. In this case, you need to configure routes using nested routines.

The method is to use children to set the child routing in the nested path.

var routes = [
  {
    path: '/user'.component: User,
    children: [{// Indicates that the path property value of /user/hobby does not require a slash /
        path: 'hobby'.component: UserHobby
      },
      { / / show/user/info
        path: 'info'.component: UserInfo,
        children: [{/ / show/user/info/school
            path: 'school'.component: UserInfoSchool
          },
        ]
      }
    ]
  }
]
Copy the code

Programmatic navigation

Programmatic navigation means setting up navigation through methods.

Router.push () is used to navigate to a new URL.

vm.$router.push('/user')
// Object structure parameters
vm.$router.push({path: '/user'})
vm.$router.push({path: '/user/123'})
Copy the code

The to attribute of

can also use the property object structure when binding is used. The Vue calls router.push() when parsing.

<router-link :to="{ path: '/user/700' }">The user 700</router-link>
Copy the code

After routing

Add the name attribute when setting up the route to make it easier to process the route.

var routes = [
  {
    path: '/user/:id/info/school'.name: 'school'.component: School
  }
];
Copy the code

In router.push(), navigate to the route by name, and set parameters by params.

vm.$router.push({ name: 'school'.params: { id: 10}})Copy the code

Can also be used in

.

<router-link :to="{ name: 'school', params: { id: 10 } }">School 10</router-link>
Copy the code

Note that the path and name modes cannot be used together.

redirect

The Redirect attribute is used to redirect routes to prevent unexpected situations.

var routes = [ { path: '/', component: Index }, { path: '/category/:id', component: {path: '/ Category ', redirect: '/'}];Copy the code

The alias

An alias is a way to beautify a path. Using the alias attribute to beautify the path, the user sees the address bar path short and beautiful.

var routes = [
  {
    path: '/user/:id/info/school/:date',
    name: 'school',
    component: School,
    alias: '/:id/:date'
  }
]
Copy the code

use

<router-link :to="{ name: 'school', params: { id: 10, date: '0612'} }">School of information</router-link>
<router-link to=20/1234 "/">School Information 2</router-link>
Copy the code

Navigation guard

Operations performed before each route is executed. It is used in scenarios such as unlogged-in users and login hops.

// Set the navigation guard
router.beforeEach(function (to, from, next) {
  // console.log(to, from);
  // Next () Navigation guard finished, proceed to the next navigation
  // next(false) terminates the next navigation
  if (to.path === '/user') {
    // Route jump
    next('/category');
  } else{ next(); }})Copy the code

Each navguard needs to execute next() once, which means that the navguard operation is finished, otherwise the navigation route cannot be entered.

The History mode

The Vue Router uses Hash mode by default because it is more compatible, but also provides History mode.

This should be set using the mode option of the Vue Router instance, which makes the URL more beautiful, but also requires backend support to avoid problems and prevent the refresh from missing the path.

var router = new VueRouter({
  mode: 'history'.routes: [{path: '/'.component: Index },
    { path: '/user'.component: User },
    { path: '/category'.component: Category },
  ]
})
Copy the code