最近研究vue-router单页转跳而不向服务器请求的原理,vue
主要是HTML5 history以及hash的应用,支持history时使用history模式vue-router
下面详细学习了一下经常使用的history相关的API跨域
经常使用API:浏览器
1.history.length:服务器
返回当前页面所产生的历史记录个数,即在同一个浏览器tab下产生的历史记录;函数
2.history.pushState(state,title,URL):学习
向浏览器新增一条历史记录,可是不会刷新当前页面(不会重载),其中state为对象,能够用做携带信息用,title:目前来看没啥用通常为空或null,URL:即要更改页面的URL,且必须同源,不能跨域;spa
3.history.replaceState(state,title,URL):code
更改当前浏览器的历史记录,即把当前执行此代码页面的记录给替换掉,参数与第二条相同;router
4.history.back()、history.forward()、history.go():
分别为前进一个历史,后退一个,history.go(Number),其中Number可正可负,即向前或向后若干个记录
5.history.state:
返回当前页面状态参数,此参数通常由history.pushState(state,title,URL);以及history.replaceState(state,title,URL);附带的state值,例子以下:
当前页面为http://example.com
history.pushState({a:1},null,"test1");//http://example.com/test1 history.state; //{a:1} history.pushState({b:2},null,"test2");//http://example.com/test2 history.state; //{b:2} history.back(); //http://example.com/test1 history.state; //{a:1} history.back(); //http://example.com history.state; //null
上面例子应该已经很明确的代表state的取值,即当前页面的状态值,没有状态值为null;
6.history事件onpopstate:
window.onpopstate = function(e){ console.log(e.state); }
在history.back(),history.forward(),history.go()时触发此事件,可是在history.pushState();history.replaceState();时并不会触发此事件,事件内能够获取到state状态值
由此能够看出vue-router中push()、go()等函数的一些端倪,可是vue-router比这个要复杂,
history是其基础之一