前端路由hash与history下

一、hashHistory

每一次改变 hash(window.localtion.hash),都会在浏览器访问历史中增加一个记录

利用 hash 的以上特点,就可以来实现前端路由"更新视图但不重新请求页面"的功能了。

HashHistory拥有两个方法,一个是push, 一个是replace;

HashHistory.push()----将新路由添加到浏览器访问历史的栈顶

push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
  this.transitionTo(location, route => {
    pushHash(route.fullPath)
    onComplete && onComplete(route)
  }, onAbort)
}

function pushHash (path) {
  window.location.hash = path
}

 从设置路由改变到视图更新的流程:

$router.push() --> HashHistory.push() --> History.transitionTo() --> History.updateRoute() --> {app._route = route} --> vm.render()

 

解析:

1 $router.push() //调用方法

2 HashHistory.push() //根据hash模式调用,设置hash并添加到浏览器历史记录(添加到栈顶)(window.location.hash= XXX)

3 History.transitionTo() //监测更新,更新则调用History.updateRoute()

4 History.updateRoute() //更新路由

5 {app._route= route} //替换当前app路由

6 vm.render() //更新视图

  

 二、HTML5History

History interface 是浏览器历史记录栈提供的接口,通过back()、forward()、go()等方法,我们可以读取浏览器历史记录栈的信息,进行各种跳转操作。
从 HTML5开始,History interface 提供了2个新的方法:pushState()、replaceState() 使得我们可以对浏览器历史记录栈进行修改:

window.history.pushState(stateObject,title,url)
window.history,replaceState(stateObject,title,url)

  

原文地址:https://www.cnblogs.com/jiox/p/14530776.html