vue手写hash router

阅读 93

2022-03-16

const Vue
class HVueRouter {
  constructor(options) {
    this.$options = options
    //  当前hash路径响应式化
    //  当hash变化时 组件的render函数重新调用 重新渲染组件
    Vue.util.defineReactive(this, 'current', '/')
    //  监听url变化
    window.addEventLister('hashchange', this.onHashChange.bind(this))
    window.addEventLister('onload', this.onHashChange.bind(this))
  }
  onHashChange() {
    this.current = window.location.hash.slice(1)
  }
}

HVueRouter.install = (_Vue) => {
  Vue = _Vue
  //  获取根实例的router配置选项
  Vue.mixin({
    beforeCreate() {
      if(this.$options.router){
        Vue.prototype.$router = this.$options.router
      }
    }
  })
  //  注册全局路由组件
  Vue.component('router-link', {
    props: {
      to: {
        type: String,
        required: true
      }
    },
    render(h) {
      return h('a', { attrs: { herf: '#' + this.to } }, this.$slots.default)
    }
  })
  
  Vue.component('router-view', {
    render(h) {
      let component = null
      this.$router.$options.routes.forEach(route => {
        if(route.path === this.current) {
          component = route.component
        }
      })
      return h(component)
    }
  })
}

export default HVueRouter

精彩评论(0)

0 0 举报