Vue Router
两种模式
两种常用的路由模式:hash模式和history模式。
- Hash模式使用URL中的哈希值(即 # 后面的部分)来模拟路由。当URL的哈希值发生变化时,Vue Router可以根据哈希值的变化来匹配相应的路由并展示相应的组件。
- 兼容性好
- 刷新页面不会出现 404
- History模式使用HTML5的history API来实现路由功能。它利用了浏览器的**pushState()和replaceState()**方法来修改URL,而不会引起页面的刷新。
- 更美观的 URL
- 需要服务器配置,否则刷新会出现 404
其实不在浏览器环境的话,还有一种abstract模式
监听实现
hash 简易实现
// hash 简易实现
// 核心实现原理
class HashRouter {
constructor() {
// 监听 hashchange 事件
window.addEventListener('hashchange', () => {
this.handleRoute()
})
}
handleRoute() {
// 获取当前 hash 值
const hash = window.location.hash.slice(1)
// 根据 hash 值匹配对应的组件
this.matchComponent(hash)
}
}history 简易实现
class HistoryRouter {
constructor() {
// 监听 popstate 事件
window.addEventListener('popstate', () => {
this.handleRoute()
})
}
push(path) {
// 使用 History API 修改 URL
window.history.pushState({}, '', path)
this.handleRoute()
}
replace(path) {
// 替换当前历史记录
window.history.replaceState({}, '', path)
this.handleRoute()
}
handleRoute() {
// 获取当前路径
const path = window.location.pathname
// 匹配对应组件
this.matchComponent(path)
}
}router-link
router-view
H5 history API
// 在history中向后跳转
window.history.back();
window.history.go(-1);
// 向前跳转
window.history.forward();
window.history.go(1);
// 当前页
window.history.go(0);
//pushState()需要三个参数:一个状态对象,一个标题(目前被忽略)和一个URL(可选的)。
var stateObj = { foo: 'bar' };
window.history.pushState(stateObj, 'page 2', 'bar.html');