vue路由
history模式
利用h5新特性,window.history.pushState()和window.history.replaceState()
参数:
window.history.pushState(state,title,url)
state可以是任意对象,用来携带路由信息。
先pushState然后replaceState就实现了地址转换,而且有历史。
example
<body>
<script>
window.onpopstate = function(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
function fn1(){
window.history.pushState({foo: "bar0"},"page1",'test.html')
window.history.replaceState({foo: "bar1"},"page1",'data/a.html')
document.getElementById('view').innerHTML = '我换了+'+Math.random()
}
function fn2(){
window.history.pushState({foo: "bar2"},"page2",'/')
window.history.replaceState({foo: "bar3"},"page2",'data/b.html')
document.getElementById('view').innerHTML = '我换了+'+Math.random()
}
</script>
<button onclick="fn1()">换地址</button>
<button onclick="fn2()">换地址2</button>
<div>
<h1 id='view'>路由改变后,替换内容</h1>
</div>
</body>
hash模式
URL添加#后是默认定位到ID元素
example
<body onload="console.log(location.href)">
<script>
window.onpopstate = function(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
function fn1(){
location.href += '#qwe'
document.getElementById('view').innerHTML = '我换了+'+Math.random()
}
</script>
<button onclick="fn1()">改变地址</button>
<div>
<h1 id='view'>路由改变后,替换内容</h1>
</div>
</body>
区别:
- hash颜值高
- 刷新页面,请求后台的地址不一样。history会按照地址栏的地址请求,hash模式会去掉#之后的内容。(history模式所有的地址,如果后端不做特殊处理,就会404。history这种模式要玩好,还需要后台配置支持……所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。)