SPA前端路由原理

單頁應(yīng)用

SPA(single-page application)

維基百科:是一種網(wǎng)絡(luò)應(yīng)用程序或網(wǎng)站的模型,它通過動態(tài)重寫當(dāng)前頁面來與用戶交互,而非傳統(tǒng)的從服務(wù)器重新加載整個新頁面。

reactvue,等框架,通過使用一個html文件提供一個掛載點,剩下的就交給js去生成。通過動態(tài)加載資源來改變頁面而不是像傳統(tǒng)的刷新整個頁面,從而達(dá)到切換頁面不需要刷新頁面的效果。

  <html>
    <body>
        <div id="app"></div>
        <!-- built files will be auto injected -->
    </body>
</html>

路由

那么問題來了,既然只有一個html,那是不是相當(dāng)于只有一個url,那么瀏覽器就無法記錄路由的變化,那么瀏覽器前進(jìn)、后退功能都沒用了。前端路由就是為了來解決這樣的問題的。前端路由主要有hashhistory兩種實現(xiàn)方式。

hash

是什么

hash就是在url后加上#和后面的字符。例如localhost:8080/#/page1, 這里的#/page1就是hash。

如何達(dá)到目的

hash的變化不會導(dǎo)致瀏覽器發(fā)送請求,hash改變會觸發(fā)hashchange,瀏覽器的前進(jìn)、后退也能操作他?;谶@三點就能實現(xiàn)前端路由。

實現(xiàn)

// hashrouter.js
class HashRouter {
  constructor() {
    // 儲存各個路由對應(yīng)回調(diào)方法
    this.routers = {};
  }
  // 注冊理由
  registry(hash, callback = () => {}) {
    this.routers[hash] = callback;
  }
  // 刷新
  refresh() {
    // 沒有hash 默認(rèn) /
    const hash = location.hash.slice(1) || "/";
    if (this.routers.hasOwnProperty(hash)) {
      this.routers[hash]();
    } else {
      // 這里匹配不到hash的話,可以自定義一個404界面
      this.routers["/not-found"]();
    }
  }
  // 初始化
  init() {
    window.addEventListener("load", this.refresh.bind(this));
    window.addEventListener("hashchange", this.refresh.bind(this));
  }
}

// index.html
<html>
<body>
    <div id="root"></div>
    <div>
        <a href="#/">page</a>
        <a href="#/page1">page1</a>
        <a href="#/page2">page2</a>
        <a href="#/o-my-god">not-fount</a>
    </div>
    <script src="./hashrouter.js"></script>
    <script>
        const hashRouter = new HashRouter()
        hashRouter.init()
        const changeHtml = function(text) {
            document.getElementById('root').innerText = text
        }
        hashRouter.registry('/', () => changeHtml('page'))
        hashRouter.registry('/page1', () => changeHtml('page1'))
        hashRouter.registry('/page2', () => changeHtml('page2'))
        hashRouter.registry('/not-found', () => changeHtml('沒有找打頁面'))
    </script>
</body>
</html>
// hashRouterRun.js
// 這個可有可無,直接打開本地文件效果一樣,只為了url好看點
// 現(xiàn)在我們通過 localhost:8081 去訪問
var express = require("express");
var fs = require("fs");
var app = express();
app.use("/", express.static(__dirname + "/hashRouter"));
app.listen(8081);
console.log("Express server started");

效果

hashrouter

history

是什么

允許操作瀏覽器的曾經(jīng)在標(biāo)簽頁或者框架里訪問的會話歷史記錄。

如何達(dá)到目的

在H5之前,history主要使用 go,forward,back這幾個方法,使用場景只能用于頁面跳轉(zhuǎn)。
在H5之后,history有了幾個新的apipushState,replaceState,可以用來添加或修改歷史記錄,這樣我們就能夠達(dá)到保存每一個路由的目的。

實現(xiàn)

class HistoryRouter {
  constructor() {
    // 儲存各個路由對應(yīng)回調(diào)方法
    this.routers = {};
  }
  // 注冊理由
  registry(path, callback = () => {}) {
    this.routers[path] = callback;
  }
  // 刷新
  // type: 1 | 2
  refresh(path, type) {
    if (!this.routers.hasOwnProperty(path)) {
      path = "/not-found";
    }
    if (type === 1) {
      history.pushState({ path }, null, path);
    } else {
      history.replaceState({ path }, null, path);
    }
    this.routers[path]();
  }
  init() {
    window.addEventListener(
      "load",
      () => {
        const currentUrl = location.href.slice(location.href.indexOf("/", 8));
        this.refresh(currentUrl, 2);
      },
      false
    );
    // 瀏覽器 前進(jìn)后退
    window.addEventListener(
      "popstate",
      () => {
        const currentUrl = history.state.path;
        this.refresh(currentUrl, 2);
      },
      false
    );
  }
}
<html>
<body>
    <style>
        a {
            cursor: pointer;
            color: blue;
        }
    </style>
    <div id="root"></div>
    <div>
        <a onclick="onChangeRouter('/')">page</a>
        <a onclick="onChangeRouter('/page1')">page1</a>
        <a onclick="onChangeRouter('/page2')">page2</a>
        <a onclick="onChangeRouter('/o-my-god')">not-fount</a>
    </div>
    <script src="./historyRouter.js"></script>
    <script>
        const onChangeRouter = function(path) {
            historyRouter.refresh(path, 1)
        }
        const historyRouter = new HistoryRouter()
        historyRouter.init()
        const changeHtml = function(text) {
            document.getElementById('root').innerText = text
        }
        historyRouter.registry('/', () => changeHtml('page'))
        historyRouter.registry('/page1', () => changeHtml('page1'))
        historyRouter.registry('/page2', () => changeHtml('page2'))
        historyRouter.registry('/not-found', () => changeHtml('沒有找打頁面'))
    </script>
</body>
</html>
history-router

到此,前端做得東西算是完成了,但是,還需要后臺配置支持的。

后端邏輯

用history的方式實現(xiàn)前端路由,刷新頁面時候,服務(wù)端是無法識別這個url的,因為spa只有一個html,所以請求別的不存在的頁面會請求不到資源。
后端需要做的就是匹配所有存在的url并返回那個唯一的html,遇到不存在的就返回一個not-found頁面。

var express = require("express");
var fs = require("fs");

var app = express();

const allRoutes = ["/", "/page1", "/page2", "/not-found"];
// 處理匹配不到路由的情況
app.use(function(req, res, next) {
    if (!allRoutes.includes(req.url) && req.url.indexOf(".") < 0) {
        res.sendFile(__dirname + "/historyRouter/index.html");
    } else {
        next();
    }
});

app.use("/", express.static(__dirname + "/historyRouter"));
allRoutes.forEach((r) => {
    app.use(`${r}`, express.static(__dirname + "/historyRouter/index.html"));
});
app.listen(8082);
console.log("Express server started");

可見,現(xiàn)在刷新頁面和遇到不存在的頁面也沒有問題了


history路由

總結(jié)

hash模式:

  • 優(yōu)點:1.不需要后端配合;2.兼容性更好,可以兼容到IE8;
  • 缺點:1.比較丑;2.會導(dǎo)致錨點失效。3.hash必須有變化才會添加記錄;

history模式:

  • 優(yōu)點:1.好看;2.能添加相同記錄;
  • 缺點:1.需要服務(wù)端配合;

參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容