1.vue路由的两种模式
hash模式:
比如 'http://www.baidu.com/#/abc' hash 的值为 '#/abc'
它的特点在于:hash 虽然出现 URL 中,但不会被包含在 HTTP 请求中,因此改变 hash 不会重新加载页面
但是会触发 onhashchange 事件,所以我们可以监听,然后渲染自己要渲染的组件,达到路由的效果
history模式:
通过 HTML5 中新增的 pushState() replaceState() 方法
应用于浏览器的历史记录,在已有的 go(),back(),forward() 的基础之上,它们提供了对历史记录进行修改的功能
当它们执行修改时,虽然改变了当前的 URL,但你浏览器不会立即向后端发送请求
我们可以通过 onpopstate 事件,监听 history 的变化,然后渲染自己要渲染的组件,达到路由的效果
2.pushState和replaceState的用法
history.pushState(state, title, url)
history.replaceState(state, title, url)
3.实现原理
<div>
<h2>history</h2>
<a class="history">home1</a>
<a class="history">about1</a>
<h2>hash</h2>
<a class="hash">home2</a>
<a class="hash">about2</a>
</div>
window.onload = function(){
document.querySelectorAll('.history').forEach(item => {
item.addEventListener('click', e => {
e.preventDefault();
let link = item.textContent;
window.history.pushState({
name: 'api'
}, '', link);
})
});
window.addEventListener('popstate', (e) => {
console.log({
location: location.href,
state: e.state
})
});
document.querySelectorAll('.hash').forEach(item => {
item.addEventListener('click', e => {
e.preventDefault();
let link = item.textContent;
location.hash = link;
}, false)
});
window.addEventListener('hashchange', () => {
console.log({
location: location.href,
hash: location.hash
})
}, false)
}