Introduce the hash

When rendering using Vue or React, there are usually hash routes and history routes.

Pros and cons of Hash

Advantages:

  • Only the front end needs to configure the routing table, but the back end does not need to participate
  • Good compatibility, browser can support
  • Changes in the hash value do not send requests to the back end, but belong to front-end routes

Disadvantages:

  • The hash value must be preceded by a #, which is not in accordance with the URL specification and is not beautiful
  • The server cannot accurately track the front-end routing information
  • Conflicts with the anchor location element

Implements front-end routing using Hash

Listening for changes in the HASH in the URL triggers a Hashchange event in which we can render different content to implement front-end routing.

Declare a Router

class Router {
  constructor(params) {
    this.cache = params.router;
    this.init();
  }

  // Initializes adding listener to browser hashchange and dom loaded functions
  init() {
    window.addEventListener('hashchange'.() = > {
      this.trigger();
    });
    window.addEventListener('load'.() = > {
      this.trigger(); })};// Matches the hash callback function and triggers
  trigger() {
    const hash = location.hash.slice(1) | |'default';
    const cache = this.cache;
    for (const r in cache) {
      if (cache.hasOwnProperty(r)) {
        const reg = this.initRegexps(r);
        if (reg.test(hash)) {
          document.getElementById('app').innerHTML = cache[r]
        }
      }
    }

  };

  /** * rematches the cache key and returns the first rematch such as /,.+-? $#{}[]] keyword and the keyword before the translation character \ * second re match () to indicate () the internal content of the optional * third re match: after the/can accept any character until the next / * fourth re match * after the * can accept any character */
  initRegexps(route) {
    route = route.replace(/[/,.+\-?$#{}\[\]]/g.'\ \ $&')
        .replace(/ \ [(. *?) \)/g.'(? : $1)? ')
        .replace(/(\/\w? :\w+)+/g.'\ / (+) [^ /]')
        .replace(/\*\w*/g.'(/ ^? *?) ');

    return new RegExp(A '^' + route + '$');
  };

  // Returns the matched re, providing arguments to the callback function
  getParams(reg, hash) {
    return reg.exec(hash).slice(1); }}Copy the code

On the HTML

<! -- Menu area -->
<div>
    <a href="#/index">index</a>
</div>
<div>
    <a href="#/det">det</a>
</div>
<! -- Display content area -->
<div id="app"></div>

Copy the code

The router is configured and triggered.

const router = {
    "/index": '< div > index content < / div >'."/det": '< div > det content < / div >'
  }
  new Router({
    router,
    templateId: 'app'
  });
Copy the code