const Vue
class HVueRouter {
constructor(options) {
this.$options = options
// 当前hash路径响应式化
// 当hash变化时 组件的render函数重新调用 重新渲染组件
Vue.util.defineReactive(this, 'current', '/')
// 监听url变化
window.addEventLister('hashchange', this.onHashChange.bind(this))
window.addEventLister('onload', this.onHashChange.bind(this))
}
// 路由映射表
this.routeMap = {}
options.routes.forEach(route => {
this.routeMap[route.path] = route
})
onHashChange() {
this.current = window.location.hash.slice(1)
}
}
HVueRouter.install = (_Vue) => {
Vue = _Vue
// 获取根实例的router配置选项
Vue.mixin({
beforeCreate() {
if(this.$options.router){
Vue.prototype.$router = this.$options.router
}
}
})
// 注册全局路由组件
Vue.component('router-link', {
props: {
to: {
type: String,
required: true
}
},
render(h) {
return h
vue手写hash router
于 2022-03-16 11:46:57 首次发布