程序员的知识教程库

网站首页 > 教程分享 正文

前端开发:带你深入理解路由两种模式

henian88 2024-10-28 15:47:28 教程分享 4 ℃ 0 评论

无论是React还是Vue前端框架渲染时,通常有hash和history两种路由方式。hash路由模式通过监听url中hash变化渲染不同的内容,它不会向服务器发送请求。history路由模式是监听url路径变化,需要客户端和服务端支持。

一、Hash路由

hash路由通过事件hashchange监听url中hash变化,在首次进入页面的时候此事件并不会执行,需要结合load事件监视首次加载的情况。那么接下来简单封装一下hashRouter。

class HashRouter {

// 当前路径URL

currentUrl = "";

constructor() {

this.callback =

this.callback.bind(this);

window.addEventListener("load", this.callback);

window.addEventListener("hashchange", this.callback);

}

// 当hash变化的时候执行的回调函数

callback() {

// 用来获取url中的hash值,如:#/home

→ /home

let path =

this.getHashPath(location.hash);

this.currentUrl = path;

}

getHashPath(url) {

return url.slice(1);

}

}

二、History路由

history路由会使用到window.history对象的方法,它提供的方法使用操作浏览器的会话历史记录。它提供的方有:

back():

后退到浏览器会话历史上一次;

forward():

前进到浏览器会话历史下一次;

go(number):

转到指定某一次浏览器会话历史,正数为前进,负数为后退;

pushState(state,title,url):

前进到指定URL,会将URL数据push进会话历史中;

replaceState(state,title,url):

将URL替换当前路径;

以上几种方式只会修改当前页面的URL,并不会发送请求。刷新浏览器后,会向服务器发送http网页请求,因此如果使用history路由模式,需要服务端配置。

使用history路由模式时,需要监听路由变化,window提供的有popstate事件,但是这个事件只能当back,forward,go三个方法执行的时候才会执行,pushState和replaceState执行时并不会触发。针对这种情况可以使用window.dispatchEvnet去触发popstate事件回调。

class HistoryRouter {

currentUrl = "";

constructor() {

this.callback =

this.callback.bind(this);

this.addStateListener();

// 添加load及页面跳转执行的监听

window.addEventListener("load", this.callback);

window.addEventListener("popstate", this.callback);

}

addStateListener() {

const listener = function

(type) {

let hisFn =

history[type];

return function () {

// 调用history的pushState,reaplaceState事件

let fn =

hisFn.apply(this, arguments);

let e = new

Event("popstate");

e.arguments =

arguments;

// 通过window.dispatchEvent触发popstate事件

window.dispatchEvent(e);

return fn;

};

};

window.history.pushState =

listener("pushState");

window.history.replaceState =

listener("replaceState");

}

callback() {

this.currentUrl =

location.pathname;

}

}

总结

hash路由模式通过hashchange监听hash变化,history模式下通过对pushState及replace方法重写,通过dispatchEvent调用popstate回调。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表