SPA前端路由原理(前端spa的概念)
单页应用
SPA(single-page application)
维基百科:是一种网络应用程序或网站的模型,它通过动态重写当前页面来与用户交互,而非传统的从服务器重新加载整个新页面。
像 react、vue,等框架,通过使用一个html文件提供一个挂载点,剩下的就交给 js 去生成。通过动态加载资源来改变页面而不是像传统的刷新整个页面,从而达到切换页面不需要刷新页面的效果。
<html> <body> <div id="app"></div> <!-- built files will be auto injected --> </body> </html> 复制代码
路由
那么问题来了,既然只有一个html,那是不是相当于只有一个url,那么浏览器就无法记录路由的变化,那么浏览器前进、后退功能都没用了。前端路由 就是为了来解决这样的问题的。前端路由主要有 hash 和 history 两种实现方式。
hash
是什么
hash 就是在url后加上 # 和后面的字符。例如 localhost:8080/#/page1 , 这里的 #/page1 就是hash。
如何达到目的
hash的变化不会导致浏览器发送请求,hash改变会触发 hashchange ,浏览器的前进、后退也能操作他。基于这三点就能实现前端路由。
实现
// hashrouter.js class HashRouter { constructor() { // 储存各个路由对应回调方法 this.routers = {}; } // 注册理由 registry(hash, callback = () => {}) { this.routers[hash] = callback; } // 刷新 refresh() { // 没有hash 默认 / 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好看点 // 现在我们通过 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"); 复制代码
效果
history
是什么
允许操作浏览器的曾经在标签页或者框架里访问的会话历史记录。
如何达到目的
在H5之前,history主要使用 go,forward,back这几个方法,使用场景只能用于页面跳转。 在H5之后,history有了几个新的api pushState,replaceState,可以用来添加或修改历史记录,这样我们就能够达到保存每一个路由的目的。
实现
class HistoryRouter { constructor() { // 储存各个路由对应回调方法 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 ); // 浏览器 前进后退 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 的方式实现前端路由,刷新页面时候,服务端是无法识别这个 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"); 复制代码
效果
可见,现在刷新页面和遇到不存在的页面也没有问题了
总结
hash模式
优点:1.不需要后端配合;2.兼容性更好,可以兼容到IE8;
缺点:1.比较丑;2.会导致锚点失效。3.hash必须有变化才会添加记录;
history模式
优点:1.好看;2.能添加相同记录;
缺点:1.需要服务端配合;
作者:基金小张
链接:https://juejin.cn/post/7036726061572784135