自己实现vue-router
实现基本路由功能
创建路由实例需要管理路由映射关系,并提供核心API。以下代码展示如何初始化路由:
class VueRouter {
constructor(options) {
this.routes = options.routes || []
this.mode = options.mode || 'hash'
this.routeMap = this.createRouteMap()
this.current = this.getInitialRoute()
window.addEventListener('load', () => {
this.updateView(this.current.path)
})
window.addEventListener('hashchange', () => {
this.current = this.getCurrentRoute()
this.updateView(this.current.path)
})
}
}
创建路由映射表
将路由配置转换为键值对形式便于查找:

createRouteMap() {
return this.routes.reduce((map, route) => {
map[route.path] = route.component
return map
}, {})
}
获取当前路由
根据不同模式解析当前URL:
getCurrentRoute() {
let path = ''
if (this.mode === 'hash') {
path = window.location.hash.slice(1) || '/'
} else {
path = window.location.pathname || '/'
}
return { path }
}
视图更新机制
通过响应式数据驱动视图变化:

class VueRouter {
// ...
init(app) {
this.app = app
defineReactive(this, 'current', this.getCurrentRoute())
}
updateView(path) {
const component = this.routeMap[path] || { template: '<div>Not Found</div>' }
this.app.currentComponent = component
}
}
路由安装插件
实现install方法供Vue.use()调用:
VueRouter.install = function(Vue) {
Vue.mixin({
beforeCreate() {
if (this.$options.router) {
this._router = this.$options.router
this._router.init(this)
Vue.util.defineReactive(this, '_route', this._router.current)
}
}
})
Vue.component('router-link', {
props: ['to'],
render(h) {
return h('a', {
attrs: { href: '#' + this.to },
on: { click: this.navigate }
}, this.$slots.default)
},
methods: {
navigate(e) {
e.preventDefault()
window.location.hash = this.to
}
}
})
Vue.component('router-view', {
render(h) {
return h(this._router.routeMap[this._route.path])
}
})
}
完整使用示例
在Vue项目中集成自定义路由:
const routes = [
{ path: '/', component: { template: '<div>Home</div>' } },
{ path: '/about', component: { template: '<div>About</div>' } }
]
const router = new VueRouter({
routes,
mode: 'hash'
})
new Vue({
el: '#app',
router
})
注意事项
实现过程中需要考虑浏览器兼容性、路由守卫、动态路由等高级功能。上述实现提供了核心功能的最小化示例,实际生产环境建议使用官方vue-router。






