<a href=‘#/index‘ class=‘hashlink‘>首页</a>
var aObjs = document.querySelectorAll(‘.hashlink‘);
aObjs.forEach(item => {
item.addEventListener(‘click‘, function(e){
e.preventDefault();
let link = item.textContent;
location.hash = link;
}
}, false)
window.addEventListener(‘hashchange‘, function(){
// 根据更改后的hash值切换组件
}, false)
注意:hash值只是#号后面的内容
var aObjs = document.querySelectorAll(‘.hashlink‘);
aObjs.forEach(item => {
item.addEventListener(‘click‘, function(e){
e.preventDefault();
let link = item.textContent;
if(!!window.history && window.history.pushState){
history.pushState({name: ‘history‘, link, link})
}
}
}, false)
history.addEventListener(‘popstate‘, function(){
})
注意:当浏览器不支持history模式时,会默认降级到hash模式处理
只有在history对象改变时触发,如果仅仅调用pushState或replaceState事件不会触发。调用history.go或history.back或history.forward会触发。
当切换时加载的不是同一文档也不会触发。
原文:https://www.cnblogs.com/ashen1999/p/12816897.html