模拟 VueRouter 2

83 阅读1分钟
const router = new VueRouter({ routes: [ {name: 'home', path: '/', component: Home} ] })

前面我们已经实现了 VueRouter 作为 Vue 插件所需的 install 方法,接下来就需要实现 VueRouter 的构造函数,在此之前,我们先了解一下 vueRouter 这个类有哪些方法和属性,再一一实现。

VueRouter 的属性

options

构造函数中传入的对象,包含 routes 路由规则。

routeMap

options 中的 routes 路由规则解析出来,以键值对的形式存储在 routeMap 中,键为路由地址,值为路由组件。

data

data 是一个响应式对象,因为其中包含 current 属性用来记录当前的路由地址,需要监听当前路由地址的变化,从而使对应的组件也自动更新。默认当前路由地址为 '/'

我们可以使用 Vue 提供的 observable 方法将传入的对象转换为一个响应式对象。

构造函数中设置属性

constructor(options){
    this.options = options
    this.routeMap = {}
    this.data = _Vue.observable({
       current:"/"
    })
}

VueRouter 的方法

init

在构造函数中调用的初始化方法,其中调用了以下3个方法。

createRouteMap

初始化 routeMap 属性,将传入的 routes 路由规则转换为键值对的形式,为了方便当路由地址变化时快速找到对应的路由组件。

createRouteMap(){
    this.options.routes.forEach(route => {
       this.routeMap[route.path] = route.component
    });
}

initComponents

创建 router-linkrouter-view 两个组件。

initEvent

注册 popState 事件,监听浏览器历史的变化。

完整代码

let _Vue = null
class VueRouter {
    static install(Vue){ ... }
    constructor(options){
        this.options = options
        this.routeMap = {}
        this.data = _Vue.observable({
            current:"/"
        })
        this.init()

    }
    init(){
        this.createRouteMap()
        this.initComponent(_Vue)
        this.initEvent()
    }
    createRouteMap(){
       this.options.routes.forEach(route => {
          this.routeMap[route.path] = route.component
       });
    }
    initComponent(Vue){ ... }
    initEvent(){ ... }
}