浅读vue-router源码,了解vue-router基本原理
项目中使用vue-router的时候,会进行以下操作(可能具体不是这么写的,但是原理一样):
- 定义映射关系routes;
- 定义router实例的时候传入vue和参数{routes…};
- 定义vue实例的时候,把router挂载到vue实例上。
接下来看我们写一个极简版的router源码。
- class VueRouter {
- constructor(Vue, options) {
- this.$options = options
- this.routeMap = {}
- this.app = new Vue({
- data: {
- current: \'#/\'
- }
- })
- this.init()
- this.createRouteMap(this.$options)
- this.initComponent(Vue)
- }
- // 初始化 hashchange
- init() {
- 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"><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()
- }
- }
constructor里接受参数option并作为成员属性保存下来。定义routeMap用来保存路由和组件的map结构。定义vue的实例app让current动态化。
初始化init()里监听浏览器的load和hashchange事件,当发生load和hashChange事件时触发onHashChange函数,并bind了this为当前路由器的实例。
onHashChange()做的事情是获取地址栏里的地址赋值给current。
createRouteMap()遍历传进来的options,生成routeMap
initComponent()初始化router的组件<router-link/>,<router-view/>,把router-link渲染成一个a标签,<router-view> 用render函数渲染 则根据current和routeMap渲染当前路由对应的组件。
版权声明:本文为superlizhao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。