vue-router模式
两种模式
1.hash:使用url的hash值来作为路由,支持所有浏览器。vue-router中默认使用hash模式。
默认显示:打开浏览器啊后显示的是:http://localhost:8081/#/。
2.history:HTML5 History API 和服务器配置。参考官网中HTML5 History模式。下面是通过在vue中将router设置成history模式,打开浏览器啊后显示的是:http://localhost:8080/home。
两种模式的区别
1.hash模式
hash 模式的原理是html5中的onhashchange事件,可以通过在window上监听这个事件。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>hash模式</title>
</head>
<body onhashchange="myFunction()">
<p>点击按钮修改当前url的锚点部分为 #part5</p>
<button onclick="changerPart()">点我</button>
<a href="history.html">cdsfvsd</a>
<p id="demo"></p>
<script>
console.log(window);
window.onhashchange=function(evevnt){
console.log(event);
let hash = location.hash;
console.log(hash) //#part5
}
function changerPart(){
location.hash="part5";
var x="锚点部分现在为:"+location.hash.slice(1);
document.getElementById('demo').innerHTML=x;
}
function myFunction(){
alert('部分锚点已修改!');
}
</script>
</body>
</html>
因为hash发生变化的url都会被浏览器记录下来,从而你会发现浏览器的前进后退都可以用了,同时点击后退时,页面会被切换到对应的hash值的页面,尽管浏览器没有请求服务器,但是页面状态和url关联起来。
2.history
History 对象是 window 对象的一部分,可通过 window.history 属性对其进行访问。
History 对象最初设计来表示窗口的浏览历史。但出于隐私方面的原因,History 对象不再允许脚本访问已经访问过的实际 URL。唯一保持使用的功能只有 back()、forward() 和 go() 方法。
history.go(-2);//后退两次
history.go(2);//前进两次
history.back(); //后退
hsitory.forward(); //前进
2.1 pushState,replaceState是新增的两个方法,两个参数一样:
params {
state:存储JSON字符串,可以用在popstate事件中,可以通过locaton.state获取。
title:现在大多数浏览器不支持或者忽略这个参数,最好用null代替
url:任意有效的URL,用于更新浏览器的地址栏,并不在乎URL是否已经存在地 址列表中。更重要的是,它不会重新加载页面。
}
2.2 pushState()和replaceState()的区别
pushState()是在history栈中添加一个新的条目,replaceState()是替换当前的记录值。用pushState的时候会产生一条新的history,replaceState则不会产生。
当我们使用pushState()和replaceState()进行处理时或者点击浏览器的前进后退的时候,popstate事件会被触发,通过监听popstate事件可以达到一系列功能。
var abc=document.getElementById("demo");
demo.οnclick=function(){
window.history.pushState(null,null,'?id=1');
//http://127.0.0.1:8020/hmode/history.html?id=2
history.replaceState(null, null, '?id=2');
//http://127.0.0.1:8020/hmode/history.html?id=2
}