vue路由hash和history的简单理解

476 阅读2分钟

随着前端SPA单页面应用的流行,为了实现页面跳转不会刷新就出现了前端路由的概念

前端路由的实现原理

  • 通过匹配不同的url路径,来动态渲染不同的页面 引出问题--url路径改变会造成页面的刷新

解决办法:

  • 通过hash值的变化实现

hash值就是值url # 及后边的值

window.location.hash = '/login' //在url路劲的后边添加了 #/login
console.log(window.location.hash)  // 打印结果 #/login
  1. url的路径#后边的值不会被解析--> 改变不会造成页面的刷新(不会发出新的请求)
  2. window.onhashchange事件可以监听hash值的变化
//配合vue的内置component
function updateDom(){
    匹配hash值进行对应的component组件切换
}
window.addEventListener('hashchange',updateDom)
  • 通过H5的historyAPI实现
window.history.pushState(state, title[, url]) 
// state:需要保存的数据,这个数据在触发popstate事件时,可以在event.state里获取
// title:标题,基本没用,一般传 null
// url(可选值):设定新的历史记录的 url。新的 url 与当前 url 的 origin 必须是一样的,否则会抛出错误。url可以是绝对路径,也可以是相对路径。
//如 当前url是 https://www.baidu.com/a/,执行history.pushState(null, null, './qq/'),则变成 https://www.baidu.com/a/qq/,
//执行history.pushState(null, null, '/qq/'),则变成 https://www.baidu.com/qq/

window.history.replaceState(state, title, url)
// 与 pushState 基本相同,但它是修改当前历史记录,而 pushState 是创建新的历史记录

window.addEventListener('popstate', function() {
	// 监听浏览器前进后退事件,pushState 与 replaceState 方法不会触发				
});

window.history.back() // 后退
window.history.forward() // 前进
window.history.go(1) // 前进一步,-2为后退两步,window.history.length可以查看当前历史堆栈中页面的数量

history跟hash的区别

  • 兼容上hash的兼容性更强

  • 用户需求上,相对的hash从外观上会在路径上添加 # 号,用户满意度不高

  • history是直接改变的url,如果页面刷新会返回404的问题,而pash不会

                                                                  ---加油!!!