一个简单的 vue-router 的实现,不支持嵌套路由
export default class VueRouter {
constructor ({ routres}) {
this.routres = routres
this.history = new History()
this.path = window.location.hash // 初始化 path
this.history.listen((path) => {
this.path = path
this.vm.$forceUpdata()
})
}
init(vm) {
this.vm = vm
}
}
class History {
listen (callback) {
window.addEventListener('hashchange', function () {
callback && callback(window.location.hash)
})
}
}
VueRouter.install = function (Vue) {
Vue.mixin({
beforeCreate () {
this.$options.router && this.$options.router.init(this)
}
})
// router-view
Vue.component('router-view', {
functional: true,
render (createElement, { props, children, parent, data}) {
const router = parent.$options.router
const path = router.path
const matchRouter = router.routres.find(router => {
return router.path.replace(/^\//, '') === path.replace(/^#\//, '')
})
const matchComponent = matchRouter.component
return createElement(
matchComponent
)
}
})
}