路由的原理
hash模式下
<body>
<!-- router-link -->
<a href="#/">首页</a>
<a href="#about">关于</a>
<!-- router-view -->
<div id="view"></div>
</body>
<script>
// 路由原码是怎么实现的
// hash模式下
// 监听浏览器的hashchange方法,对应拿到路径,渲染对应组件;
document.addEventListener('DOMContentLoaded',()=>{
view.innerHTML = location.hash.slice(1);
})
window.addEventListener('hashchange',() => {
console.log('hashchange');
view.innerHTML = location.hash.slice(1);
})
history模式下
// history模式下
// 如果不用a标签 用span元素则
// h5中的pushState
function routerChange(pathname){
history.pushState(null,null,pathname)
view.innerHTML = location.pathname;
}
window.addEventListener('popstate',()=>{
view.innerHTML = location.pathname;
})
两个的区别:
1.hash通过锚点跳转,# url会更改,浏览器可以进行前进后退,浏览器不断刷新,不和服务器端交流(主要通过hash)
2.history无锚点无hash,需要服务端配合