关于前端:前端路由

3次阅读

共计 1994 个字符,预计需要花费 5 分钟才能阅读完成。

一. 前端路由定义

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

前端路由的实现

 前端路由分为 hash 路由和 history 路由。晚期前端路由都是基于 hash 路由实现的,所谓 hash 路由就是 url 中 #之后的局部,如:https://www.word.com#search
location.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;}
正文完
 0