前端的hash和history路由
- 0
#讨论区
00条评论
实时对话
loading...
SPA路由主要应用了hash和history来避免页面刷新,history是利用浏览历史记录栈的API实现,hash是监听location对象hash值变化事件来实现
window.location.hash
可设置或获得hash值onhashchange
可以监听hash的变化几种触发onhashchange的情况
https://zzfzzf.com/#home
,这时按下输入,浏览器发送https://zzfzzf.com
请求至服务器,请求完毕之后设置散列值为#home,进而触发onhashchange事件;<a>
标签的属性 href 可以设置为页面的元素ID如 #top,当点击该链接时页面跳转至该id元素所在区域,同时浏览器自动设置 window.location.hash 属性,地址栏中的哈希值也会发生改变,并触发onhashchange事件js
js
调用history.pushState()或history.replaceState()不会触发popstate事件 只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()或者history.forward()方法)
js
js
history.back();
history.forward();
history.go(1);
history.go(-1);
history.go(0); #刷新
const state = { 'page_id': 1, 'user_id': 5 }
const title = ''
const url = 'hello-world.html'
history.pushState(state, title, url) #不可跨域,添加 History 对象的一条记录
history.replaceState(state, title, url)#不可跨域,修改 History 对象的当前记录
window.addEventListener('popstate', (event) => {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
});
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null
history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
window.onpopstate = function(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null
history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}