Tree jam hope to bring you the fun of the front end of this article has been included github.com/littleTreem… Like to star ✨


When it comes to routing, it is generally divided into front-end routing and back-end routing. Back-end routing refers to that when users switch different urls through the browser, they will send resource requests to the server, and the server will return different pages based on different urls after matching the back-end routing. Front-end routing leaves the task of browser-server interaction (URL rule matching for page jumps) to the front-end

1. Front-end routing mode

At present, single-page application (SPA) has become the mainstream of front-end applications, and a big feature of large-scale single-page applications is that the front-end route controls the jump of the page and updates the page view without requesting the server through URL switching. Here, vue-Router is taken as an example to analyze the front-end routing modes, which mainly include two types: Hash and History modes

1.1 the hash pattern

Hash mode means that the browser does not need to make a request to the server to refresh the page by changing the hash value (similar to an anchor point). How does the browser listen for changes? The hashchange event is triggered by the change in the hash value in the URL, so we can see exactly what has happened to the hash

The hash value obtained from location.hash is #/test, assuming your browser is accessing the URL http://127.0.0.1/#/test

Route changes can be caused in three ways: page refresh, browser return operation, and new link jump. The following is the flow chart 👇


What is the implementation principle of listening for route changes in hash mode?

window.addEventListener('hashchange', this.onHashChange.bind(this)) window.addEventListener('load', Bind (this)) function onHashChange(){this.onhashchange.bind (this)) function onHashChange(){Copy the code

Interested children can study vue-Router on the hash class of the specific source code implementation point I reach rocket

1.2 the history mode

Since the introduction of the new HTML5 standard, pushState and replaceState are new apis for HTML5, which can change the URL address without sending a request. The front-end routing now has another mode of History, which does not require the # symbol to be added to the URL. It also makes the URL look nice

Let’s first look at what’s in the window.history object


History.pushState

Create a new browsing record and insert it into the browsing record queue without refreshing the browser. When refreshing the page, the content of the page remains unchanged but the address changes, the API can pass in three parameters, respectively

  • StateObject: You can pass the content of a stateObject to a new page using the pushState method
  • Title: Do not pass
  • Address (URL) : The address of the new history entry (URL does not support cross-domain);
Window. The history. PushState ({data: "test"}, "", 'http://127.0.0.1/test');Copy the code

History.replaceState:

PushState () is similar to history.pushState(), except that pushState adds a new history, while replaceState replaces the current history with the destination address

Window. The history. ReplaceState ({data: "test"}, "", 'http://127.0.0.1/test');Copy the code

popstate

Popstate is triggered when the user initiates a return operation or performs an operation such as history.go() or history.forward()

 window.addEventListener('popstate', e => {
    //todo 
 });
Copy the code

This mode also needs to be configured on the back end compared to hash mode. If the background is not configured correctly, when the user directly refreshes http://127.0.0.1/#/test in the browser, 404 will be returned. So how to solve this problem 🤔️

You will need to add the weighting to the Nginx configuration file and attach the official history vue-Router document

location / {
  try_files $uri $uri/ /index.html;
}
Copy the code

The flowchart in vue-router History mode is as follows


Interested in vue-Router on the history class specific source code implementation point I reached rocket

2. Route application

Let’s talk about some application scenarios of vue-Router

2.1 Route Interception

Route interception can be used as a front-end authentication entry, for example, to determine whether the user is logged in

mport Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const router = new Router({ routes: [ { path: '/home','' component: () => import('@/components/Home') } },{ path: '/login', name: 'login', component: (resolve) => { component: () => import('@/components/Login')}}}]}) // determine whether to Login and whether to Login to the router. BeforeEach ((to, from,) Next) => {if (to.matched. Some (res => res.meta.requireauth)) {if (localstorage.getitem ('item')) Next ({path: '/login', query: {redirect: to.fullPath} }) } } else { next() } })Copy the code

export default router

2.2 Lazy Route loading

Lazy loading, as the name implies, is to wait for loading. In SPA applications, if components are not loaded through lazy loading, the file system packaged by WebPack will be too large, which will affect user experience

export default new Router({ routes: [ { path: '/home', name: 'home', component: () = > import (' @ / components/Home ') # lazy loading into component}});Copy the code

2.3 Modular Route Management

If you’re still worried about how to manage different routes for different modules and functions, require.context() is recommended.

Use require.context to export all routes


Require.context () allows you to pass in a directory to search, a flag to indicate whether subdirectories should also be searched, and a regular expression to match files. Webpack processes the contents of require.context when you build your project

Require.context () takes three arguments:

  • Directory: indicates the path for reading files

  • UseSubdirectories: Whether to traverse a file subdirectory

  • RegExp: Regex for matching files

The practical applications are as follows: 👇


The routes export looks like this


Of course, the original way of defining routes has also changed

/* * @author: tree * @date: 2019-11-06 20:20:51 */ export default [{path: '/user/info', name: 'personalInfo', Component: () => import('@/views/user/info.vue'), meta: {title: 'account info ', keepAlive: false, showHeader: true }, }, { path: '/user/security', name: 'security', component: () => import('@/views/user/security.vue'), meta: {title: 'security Settings ', keepAlive: false, showHeader: true},},];Copy the code

2.4 Other common routing apis

  • Window.history.back () : loads the previous URL in the history list
  • Window.history.forward () : loads the next URL in the history list
  • Window.history. back(n) : Loads a page in the history list
  • Window.location. href: Returns the full URL
  • Window.location. hash: Returns the anchor part of the URL
  • Window. The location. The pathname: return URL path name

2.5 KOA-router Needs to be added