class historyRoute{
construcor() {
this.current = null;
}
}
class vueRouter {
constructor(options) {
this.mode = options.mode || 'hash';
this.routes = options.routes || [];
this.history = new historyRouter;
this.routesMap = this.createMap(this.routes)
this.init();
}
init() {
if(this.mode =='hash') {
location.hash ? '' : location.hash = '/';
window.addEventListener('load',()=>{
this.history.current = location.hash.slice(1)
})
window.addEventListener('hashchange',()=>{
this.history.current = location.hash.slice(1)
})
}else {
location.pathname ? '' : location.pathname = '/';
window.addEventListener('load',()=>{
this.history.current = location.pathname
})
window.addEventListener('popstate',()=>{
this.history.current = location.pathname
})
}
}
createMap(routes) {
return routes.reduce((pre,current)=>{
pre[current.path] = current.component;
return pre
})
}
}
vueRouter.install = function(Vue) {
Vue.mixin({
beforeCreate() {
if(this.$options && this.$options.router) {
this._root = this;
this._router = this.$options.router;
Vue.util.defineReactive(this, 'current', this._router.history)
}else {
this._root = this.$parent._root
}
}
})
Vue.component('router-view',{
render(h) {
let current = this._self._root._router.history.current;
let routesMap = this._self._root._router.routesMap;
return h(routesMap[current])
}
})
}
export default vueRouter
|