This is the 17th day of my participation in the August Text Challenge.More challenges in August


One, foreword

This article begins with the study of VueRouter source code. This article mainly involves the following contents:

  • VueRouter source code project environment construction
  • A brief introduction to the two routing modes

Second, the construction of project environment

VueRouter source project, will use vuE-CLI official provided rapid prototype development tools to build;Copy the code

2.1. Install dependencies

Install the vue – the cli:

npm install @vue/cli -g
Copy the code

Install vuE-CLI Rapid Prototyping tool:

npm install -g @vue/cli-service-global
Copy the code

Rapid prototyping tools: can quickly help developers build and run a VUE project;

2.2. Create an entry file

Once installed, you can create the entry file main.js directly in the project folder:

// Dependencies can be imported directly. When the project is started, dependencies will be automatically found
import Vue from 'vue';	

// Create a Vue instance
// If no relevant file is provided, vue-cli will be used as the default file: e.g. El :'#app'
const vm = new Vue({
  el:'#app'.render:(h) = >{  // h equals _c, createElement
    return h('h1', {}, 'Hello Vue Router'); }});Copy the code

2.3. Project Configuration

Add vue. Config. js to disable default overlay error message display:

module.exports = {
  devServer: {
    overlay: {
      warnings: false.errors: false}}}Copy the code

2.4. Start the service

Development service startup command:

vue serve main.js
Copy the code

Note: The configuration in vuE-CLI project is used by default.

Search rules for files:

  • Running vue serve directly by default will look for the entry file main.js;
  • If main.js does not exist, app.vue will continue to be found;
  • If it still cannot be found, an error is thrown;

You can directly run vue serve to start the service and view the page output. Overlay error disappears:


3. Introduction to routing modes

  • Before, in the architecture mode of the front and back end is not separated, the control of page jump is completely processed by the back end, each jump needs to visit the server and refresh the whole page;
  • Now, in the architecture mode of front and back end separation, the front end maintains the jump relationship between pages locally through a routine system, and each jump only obtains data through API interface and renders to the page.

The VueRouter contains Hash and History routing modes.

3.1. Hash Mode (default)

Hash mode (default) : Use the Hash of a URL to simulate a full URL.

Compatibility: Support for all browsers;

  • http://localhost:8080/aaa/#/bbb
  • http://localhost:8080/aaa#bbb

Features: Hash urls have Hash marks that look like anchors.

Principle of Hash mode

Hash mode relies on the browser-provided onHashchange event:

// The onHashchange event triggers the condition when the part after # in a window URL changes
window.onhashchange = function(event){
  // http://localhost:8080/aaa/#/bbb -> http://localhost:8080/aaa/#/ccc
  console.log(event.oldURL, event.newURL);
  let hash = location.hasg  // Get the hash address from the location object
  console.log(hash)         // #/ccc
}
Copy the code

See MDN: onhashchange

Advantages of Hash mode

  • When the URL changes, the page does not reload;
  • The Hash URL is recorded by the browser. You can switch to and refresh the page by clicking Forward and Back of the browser.

Disadvantages of Hash mode

  • The URL will contain a ‘#'(or possibly a ‘#/’), and the page path will be set after a ‘#’, which is ugly;
  • In onHashchange, only the URL fragment after ‘#’ can be changed;

Generally, online production projects do not adopt hash routing mode.


3.2. History Mode

History mode: requires server background configuration and support.

Compatibility: Only compatible with IE10 due to the HTML5 History API;

Example: http://localhost:8080/aaa/bbb

In contrast to Hash mode, the History mode URL does not have a # sign and is a 'normal' URL;Copy the code

Principle of History mode

VueRouter’s History mode is implemented using the browser-provided History API.

As a result, the VueRouter source code handles the History mode slightly more easily than the Hash mode;

Refer to the MDN: History API

Advantages of the History mode

  • Compared to Hash mode, the URL display in History mode is normal and beautiful;
  • Hashchange can only change the URL fragment after ‘#’, while the History API provides complete freedom;
  • Have browser history, can be “forward” and “back” page switch;
  • When the path changes, you can monitor the path change of the browser.

Disadvantages of the History mode

  • In History mode, you can go forward and backward, but when F5 refreshes, 404 is displayed.

At this time, because the F5 page refresh operation, is really to the server request page;

In hash mode, the # part of the front-end route modification is not carried by the browser when requested, so there is no problem;

Error 404 is reported when there are no related responses or resources on the server in history mode.

404 problems after single-page application packaging

Problem description

Single page application, local development all normal, packaged after access to 404;

The solution

Add a candidate resource on the server that covers all cases: if the URL doesn’t match any static resource, it should return the same index.html page that your app relies on.

Matters needing attention

With this solution, the server no longer returns the 404 error page;

To avoid this, you need to overwrite all routing cases in the Vue application and then present a 404 page.

History mode: This mode is used in the production environment but requires the support of the server. Otherwise, 404 is displayed when the page is refreshed.

Added: Abstract mode

Abstract mode: All JS modes are supported. If no browser API is detected, this mode is forced;


Four, the end

This paper introduces the environment construction and routing mode, mainly involving the following points:

  • Completed the construction of VueRouter source code project development environment;
  • Hash and History routing modes are introduced.

In the next chapter, the two routes are introduced.


Maintain a log

  • 20210818:
    • Adjust the description of “Building project Environment” and add the secondary directory;
    • Rewrite the “Introduction to Routing Pattern” section to add secondary and tertiary headings;
    • Adjust the “end” section