vue-router 源码之实现一个简单的 vue-router

2020-06-13 10:48:02易采站长站整理

window.addEventListener('load', this.onHashChange.bind(this), false);
window.addEventListener('hashchange', this.onHashChange.bind(this), false);
}

// 路由映射表
createRouteMap (options) {
options.routes.forEach(item => {
this.routeMap[item.path] = item.component;
});
}

// 注册组件
initComponent (Vue) {
Vue.component('router-link', {
props: {
to: String
},
template: '<a :href="to" rel="external nofollow" rel="external nofollow" ><slot></slot></a>'
});

const _this = this;
Vue.component('router-view', {
render (h) {
var component = _this.routeMap[_this.app.current];
return h(component);
}
});
}

// 获取当前 hash 串
getHash () {
return window.location.hash.slice(1) || '/';
}

// 设置当前路径
onHashChange () {
this.app.current = this.getHash();
}
}

最后

将 Vue 与 Hash 路由结合,监听了 hashchange 事件,再通过 Vue 的 响应机制 和 组件,便有了上面实现好了一个 vue-router。

全部源码参考这里。