1. Vue Router 核心原理
1.1 什么是前端路由?
前端路由是在单页应用(SPA)中,通过 JS 来操作 URL,从而在不重新请求页面的情况下更新视图内容。Vue Router 建立了 URL 和视图组件之间的映射关系。
1.2 实现原理
- Hash 模式:
// 核心实现原理
class HashRouter {
constructor() {
// 监听 hash 变化
window.addEventListener('hashchange', () => {
this.handleHashChange()
})
}
handleHashChange() {
const hash = window.location.hash.slice(1)
// 根据 hash 找到对应组件进行渲染
this.matchComponent(hash)
}
}
- History 模式:
// 核心实现原理
class HistoryRouter {
constructor() {
// 监听 popstate 事件
window.addEventListener('popstate', () => {
this.handleUrlChange()
})
// 重写 pushState/replaceState 方法
this.bindHistoryEvents()
}
bindHistoryEvents() {
const originalPushState = history.pushState
history.pushState = (...args) => {
originalPushState.apply(history, args)
this.handleUrlChange()
}
}
}
2. Vue2 与 Vue3 路由对比
2.1 创建方式
Vue2:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use