前端的hash和history路由

    0

SPA路由主要应用了hash和history来避免页面刷新,history是利用浏览历史记录栈的API实现,hash是监听location对象hash值变化事件来实现

hash

  1. hash即锚点
  2. window.location.hash可设置或获得hash值
  3. onhashchange可以监听hash的变化
  4. 优点是不需要服务端配合,缺点不太美观

几种触发onhashchange的情况

  1. 浏览器地址栏散列值的变化(包括浏览器的前进、后退)会触发window.location.hash值的变化,从而触发onhashchange事件
  2. 当浏览器地址栏中URL包含哈希如 https://zzfzzf.com/#home,这时按下输入,浏览器发送https://zzfzzf.com请求至服务器,请求完毕之后设置散列值为#home,进而触发onhashchange事件;
  3. 当只改变浏览器地址栏URL的哈希部分,这时按下回车,浏览器不会发送任何请求至服务器,这时发生的只是设置散列值新修改的哈希值,并触发onhashchange事件;
  4. html中<a>标签的属性 href 可以设置为页面的元素ID如 #top,当点击该链接时页面跳转至该id元素所在区域,同时浏览器自动设置 window.location.hash 属性,地址栏中的哈希值也会发生改变,并触发onhashchange事件

history

  1. window.history 属性指向 History 对象
  2. history.lenght 当前窗口访问过的网址数量
  3. 优点是美观,缺点是需要服务端配合
  4. 操作路由
js
history.back(); history.forward(); history.go(1); history.go(-1); history.go(0); #刷新
js
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 对象的当前记录

调用history.pushState()或history.replaceState()不会触发popstate事件 只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()或者history.forward()方法)

js
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}
js
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}
评论区

共有评论 0

暂无评论