手记

手动实现 简易版的 Vue-Router

let Vue
class VueRouter {
  constructor(options) {
    this.$options = options
    this.routeMap = {}
    this.$options.routes.forEach(route => {
      this.routeMap[route.path] = route
    })
    Vue.util.defineReactive(this, 'current', '/')
    window.addEventListener('hashchange', this.onHashChange.bind(this))
  }

  onHashChange() {
    this.current = window.location.hash.slice(1)
  }
}

VueRouter.install = function (_Vue) {
  Vue = _Vue
  Vue.mixin({
    beforeCreate() {
      let router = this.$options.router
      if (!router) return
      Vue.prototype.$router = router
    }
  })
  Vue.component('router-view', {
    render(h) {
      const { routeMap, current } = this.$router
      return h(routeMap[current] ? routeMap[current].component : null)
    }
  })

  Vue.component('router-link', {
    props: {
      to: {
        type: String,
        default: ''
      }
    },
    render(h) {
      return h('a', {
        attrs: {
          href: `#${this.to}`
        }
      }, this.$slots.default)
    }
  })
}

export default VueRouter
1人推荐
随时随地看视频
慕课网APP