一.前端路由定义

路由能够简略了解为一个url地址,这个地址映射到服务端可能是一个文件读取操作、一个数据库查问或者一次数据处理;而对应于前端就是一次dom操作,卸载或暗藏掉一些dom节点,展现另外一些。

前端路由的实现

前端路由分为hash路由和history路由。晚期前端路由都是基于hash路由实现的,所谓hash路由就是url中#之后的局部,如:https://www.word.com#searchlocation.hash有以下特点:1. url中的hash局部是前端状态,hash值变动不会给服务端发送音讯,只是前端状态变动。2. location.hash变动会引起浏览器的浏览记录中插入一条新的记录,这样就能够应用浏览器的后退/后退按键来扭转location.hash。3. 能够通过监听hashchange事件监听到location.hash的变动,这样就能够在hash变动是做出相应操作。

以下先实现一个hash路由和history路由的基类:

class BaseRoute  {  constructor(list) {    this.list = list;  }  render(state) {    let  ele = this.list.find(item => item.path === state);    ele = ele ? ele ? this.list.find(item => item.path === '*');    ELEMENT.innerText = ele.component;}

以下补充hash路由的实现:

class HashRoute extends BaseRoute {    constructor(list) {        super(list);        this.handler();        window.addEventListener('hashchange', this.handler.bind(this));    }    getState() {        let hash = location.hash;        return hash ? hash.slice(1) : '/';    }    handler() {        this.render(this.getState());    }    push(path) {        window.location.hash = path;    }    getUrl(path) {      const href = window.location.href;      const i = href.indexOf('#');      const base = i >= 0 ? href.slice(0, i) : href;      return base +'#'+ path;    }    replace(path) {      window.location.replace(this.getUrl(path));    }    go(n) {        window.history.go(n);    }}
在html5之后,浏览器提供了新的History api来实现url的扭转,pushState 和 replaceState 。pushState 和 replaceState 能够实现不刷新页面而扭转页面url, pushState实现向浏览历史中插入一条记录,replaceState实现将以后的浏览历史替换成新的。能够通过监听popState实现监听路由变动,但pushState和replaceState不会引起popState事件触发。故在应用pushState和replaceState时须要被动调用响应函数。

一下为history路由的实现:

class HistoryRoute extends BaseRoute {    constructor(list) {        super(list);        this.handler();        window.addEventListenter('popstate', this.handler.bind(this));    }      // 渲染页面  handler() {    this.render(this.getState());  }  // 获取 url  getState() {    const path = window.location.pathname;    return path ? path : '/';  }  // push 页面  push(path) {    history.pushState(null, null, path);    this.handler();  }  // replace 页面  replace(path) {    history.replaceState(null, null, path);    this.handler();  }   // 后退 or 后退浏览历史  go(n) {    window.history.go(n);  }}

留神: history路由须要服务端接入层(ngix)配合批改,将发送给服务端的前端路由都代理到webapp的js文件上。

location /test/mywebapp { autoindex on; index index.html; try_files $uri /test/mywebapp/index.html; }