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

Introduce it when you need it, don’t reference it when you don’t need it.

A single page application

SPA (Single Page Application) is a Single Page Application. This is when “all” (most or part of) the functionality of a web site is presented in a single page.

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

  • If a page has only one feature – multi-page application (traditional way) – it is mainly e-commerce

Advantages of single page application:

  • 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 of single-page applications:

  • 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

  • Three elements: URL, content, and mapping

There are two implementations:

  • Hash way
  • The History way

Hash way

Listen for hash changes and web content updates through the Hashchange event.

The hash is part of the URL (the part after #), and the hash modifies the URL but does not jump.

<body>
  <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>
    var container = document.getElementById('container');

    window.onhashchange = function () {
      // Get the hash in the URL
      var hash = location.hash.replace(The '#'.' ');
      // Change the content of the page according to different hash values.
      var str = ' ';
      switch (hash) {
        case '/':
          str = 'This is what the front page does.';
          break;
        case '/category':
          str = 'That's the function of categorization.';
          break;
        case '/user':
          str = 'This is a user function.';
          break;
      }
      container.innerHTML = str;
    };
  </script>
</body>
Copy the code
  • location.hashThe hash value is band#So usereplaceGet rid ofhashValue.

Hash encapsulation

Encapsulate for reuse.

  • routerThat’s the object we prepared for the routing function
  • routesIs an object that stores multiple routes, that is, urls (hashes) and content-handling functions
  • routeIs a function that defines the route,pathIs a path,callbackIs a function.
  • initMethod is used to initialize the route,
  • &&Only the one in front istrueCan execute the second
<body>
  <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>
</body>
Copy the code

Summary of Hash features:

  • Hash mode is compatible.

  • Address with #, not very beautiful.

  • The forward and backward functions are cumbersome.

The History way

The History method uses the new functionality provided by HTML5 to realize front-end routing. Compatibility is not as good as hash.

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

History.pushstate () :

  • Parameter 1: The state object associated with the current path
  • Parameter 2: Used to pass in the title (currently not supported by browsers)
  • Parameter 3: The path to which you want to set the URL, but there is no jump operation

  • Use directly.hrefProperty retrieves the value of the entire URL
  • getAttribute()Access ishrefProperty and its internal value, namely"/"."/category"."/user"These values.

Forward and backward processing

  • The forward and backward function first needs to save the routing flag when changing the URL. To change thepushState()The first argument to.
  • throughpopstateEvent listens for forward and back button actions and detectsstateIf yes, go to the corresponding path, do not return to the home page.
  • router.init()Call the initialization method to listen for forward and backward operations and process them.
<body>
  <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>
</body>
Copy the code

Vue Router

Vue.js is the official routing manager for vue. js, making building single-page applications a breeze.

The basic use

How do I install a Vue Router?

  1. Direct download/CDN
  • Latest version: unpkg.com/vue-router/…

  • Version: unpkg.com/vue-router@…

  1. npm
npm install vue-router
Copy the code

If it is an imported form, it is referenced after vue.js.

The basic structure

The Vue Router provides the

and

components for routing Settings.

Specific operation

  1. This section describes how to define routing components and set routing rules.

  1. This section describes how to define routing components and set routing rules.

  1. Create a Vue Router instance and configure routes using the Routes attribute.

  1. Create a Vue instance and inject routes using the Router attribute.

Named view


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

  • There is one or more<router-view>The default value isname="default"

In the route, the corresponding components of different views are set through the components property:

  • On the left (e.g.,default) refers to:<router-view>thename
  • On the right (e.g.,SideBar1) refers to the name of the component

<body>
  <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>
  <script src="lib/vue.js"></script>
  <script src="lib/vue-router.js"></script>
  <script>
    var SideBar1 = {
      template: '
       
sidebar 1 function
'
}; var SideBar2 = { template: The '
sidebar 2 function
'
}; var Index = { template: '
Home page function
'
}; var User = { template: '
User function
'
}; // Define routing rules var routes = [ { path: '/'.components: { // Router-view name: component configuration object default: Index, sidebar: SideBar1 } }, { path: '/user'.components: { default: User, sidebar: SideBar2 } } ]; // Create a Vue Router instance var router = new VueRouter({ routes }); // Create a Vue instance new Vue({ el: '#app', router });
</script> 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.

After the dynamic route is set to dynamic, any content in the dynamic part redirects to the same component. For example, users 1,2, and 3 all jump to the same page:

$route.params. If :id is used to set dynamic routes, then. Id is used to obtain dynamic changes.

  • here$route.params.id

<body>
  <div id="app">
    <router-link to="/user/1">User 1</router-link>
    <router-link to="/user/2">The user 2</router-link>
    <router-link to="/user/3">The user 3</router-link>

    <router-view></router-view>

  </div>
  <script src="lib/vue.js"></script>
  <script src="lib/vue-router.js"></script>
  <script>
    // Set the component
    var User = {
      template: '
       
this is the function of user {{$route.params.id}}
}; // Set routing rules var routes = [ { path: '/user/:id'.component: User } ]; var router = new VueRouter({ routes }); var vm = new Vue({ el: '#app', router });
</script> </body> Copy the code

Listening route parameter

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

  • In dynamic route switching, components are reused rather than recreated.

  • When switching between different users,$routeIt’s going to change, it’s going to callwatch, this isrouteThe content is as followsroute.params.idIs the content of the corresponding dynamic route.

Processing route parameter Transmission (single view)

The data is set up by the props of the route and received by the component props.

The sender:

  • If you set it upprops:true, used when receivedpropsTo receive — actually to receive$route.params.idThe value of theta is passed inpropsIn the

The receiving party:

<body>
  <div id="app">
    <router-link to="/user/1">User 1</router-link>
    <router-link to="/user/2">The user 2</router-link>
    <router-link to="/user/3">The user 3</router-link>

    <router-link to="/category/1">Category 1</router-link>
    <router-link to="/category/2">Category 2</router-link>
    <router-link to="/category/3">Category 3</router-link>

    <router-view></router-view>
  </div>
  <script src="lib/vue.js"></script>
  <script src="lib/vue-router.js"></script>
  <script>
    // The configuration object of the component
    var User = {
      template: This is the user {{$route.params.id}} function 
    };

    var Category = {
      props: ['id'].template: This is the classification {{id}} function  '
    };

    // Set routing rules
    var routes = [
      {
        path: '/user/:id'.component: User
      },
      {
        path: '/category/:id'.component: Category,
        props: true}];var router = new VueRouter({ routes });
    var vm = new Vue({
      el: '#app',
      router
    });
  </script>
</body>
Copy the code

Route Parameter Transmission processing (multiple views)

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

  • If the component does not need to pass a value, it can be written as default or not.

  • If you want to set static data, set an option corresponding to a component in props as an object, and the internal properties are bound to the component’s props.

<body>
  <div id="app">
    <router-link to="/user/1">User 1</router-link>
    <router-link to="/user/2">The user 2</router-link>
    <router-link to="/user/3">The user 3</router-link>

    <router-link to="/category/1">Category 1</router-link>
    <router-link to="/category/2">Category 2</router-link>
    <router-link to="/category/3">Category 3</router-link>

    <router-view name="sidebar"></router-view>
    <router-view name="sidebar2"></router-view>
    <router-view></router-view>
  </div>
  <script src="lib/vue.js"></script>
  <script src="lib/vue-router.js"></script>
  <script>
    var SideBar = {
      template:'
       
This is the SideBar component
}; var SideBar2 = { props: ["a"."b"].template:`<div>sidebar2: {{a}} {{b}}</div>` }; var User = { template:'
This is the component
of user {{$route.params.id}}
}; var Category = { props: ['id'].template: This is the component of the class {{id}} }; var routes = [ { path: "/user/:id".components: { sidebar: SideBar, default: User } }, { path: "/category/:id".components: { sidebar: SideBar, sidebar2: SideBar2, default: Category }, props: { sidebar: false.sidebar2: { a: "State 1".b: "State 2" }, default: true}}];var router = new VueRouter({ routes }) var vm = new Vue({ el: "#app", router })
</script> </body> 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.

  • usechildrenTo set the child routing in nested routines.

<body>
  <div id="app">
    <router-link to="/user">User functionality</router-link>
    <router-view></router-view>
  </div>
  <script src="./lib/vue.js"></script>
  <script src="./lib/vue-router.js"></script>
  <script>
    var User = {
      template: `
        <div>
          <h3>This is what the User component does</h3>
          <router-link to="/user/hobby">Hobby function</router-link>
          <router-link to="/user/info">The user information</router-link>
          <router-view></router-view>
        </div>`}; var UserHobby = { template: `<div>UserHobby components</div>`}; var UserInfo = { template: `<div>The UserInfo components<router-link to="/user/info/school">School of information</router-link>
          <router-view></router-view>
        </div>`}; var UserInfoSchool = { template: `<div>UserInfoSchool components</div>`}; var routes = [ { path: '/user', component: User, children: [ { path: 'hobby', component: UserHobby }, { path: 'info', component: UserInfo, children: [ { path: 'school', component: UserInfoSchool }, ] } ] } ]; var router = new VueRouter({ routes }); var vm = new Vue({ el: '#app', router });</script>
</body>
Copy the code

Programmatic navigation

Programmatic navigation means setting up navigation through methods.

  • router.push()Used to navigate to a new URL (this can be tested in the console).

  • <router-link>toattributeWhen using V-bindYou can also useAttribute object structure. usev-bindAfter binding, actuallytoWill performrouter.push()Method, so you can use the property object structure internally.

After routing

Add the name attribute when setting the route.

In push(), the route is navigated by name and the parameters are set by params.

Note: Params is used to set the route parameter. It can only be used with name. If path is used, the full URL must be used.

Can also be used in

:

<body>
  <div id="app">
    <router-link :to="{ name: 'school', params: { id: 10, a:2, b:3 } }">School 10</router-link>

    <router-view></router-view>
  </div>
  <script src="lib/vue.js"></script>
  <script src="lib/vue-router.js"></script>
  <script>
    var School = {
      template: {{$route.params}}
    };

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

    var router = new VueRouter({ routes });
    var vm = new Vue({
      el: '#app',
      router
    });
  </script>
</body>
Copy the code

redirect

Alias (routing beautification)

  • aliasMake the URL displayed in the client browser shorter and prettier, while actually visiting a more complex URL.

<body>
  <div id="app">
    <router-link :to="{name: 'school', params: {id:1, data:'0315'}}">School of information</router-link>
    <router-link to=20/1234 "/">School Information 2</router-link>
    <router-view></router-view>
  </div>
  <script src="lib/vue.js"></script>
  <script src="lib/vue-router.js"></script>
  <script>
    / / component
    var School = {
      template: '
       
School component
}; // Routing rules var router = new VueRouter({ routes: [{path: '/user/:id/info/school/:date'.name: "school".component: School, alias: ":id/:data"}}]);var vm = new Vue({ el: '#app', router });
</script> </body> Copy the code

After setting the alias, click “School Info 2” to display the url as follows:

Navigation guard

For example, some pages need to restrict users’ access rights, and they need to intercept or jump, so they need navigation guards.

  • toIndicates the route to jump to
  • fromWhere is the route coming from
  • nextiffromandtoIf the conditions are met, perform the next operation

Next can pass parameters in addition to release, such as false if the user cannot proceed with the navigation operation; If the unlogged user accesses some operations that require login, the login page is redirected.

  1. ifnext()Directly called, indicating that subsequent functions can be performed.

  1. Set up thenext(false)Indicates that subsequent operations are blocked.

  1. Route jump operation

For example, when I click on “user “(/user) I go to” category “(/category)

The History mode

Most urls use hash mode because it is more compatible, and the main feature is the hash sign in the URL.

In addition, the URL also has a history mode (no # in the URL), which needs to be set using the mode option of the Vue Router instance. This makes the URL more beautiful, but also requires backend support to avoid problems.