vue-router实现原理

104 阅读1分钟

使用vue-router的四个步骤

  1. 注册插件

    import Router from 'vue-router'
    Vue.use(Router)
    
  2. 新建router实例并导出

    const router = new Router({
      mode: 'hash',
      routes
    })
    
  3. 在根组件添加router实例

    new Vue({
      router
    })
    
  4. 添加路由视图

原理手写

let Vue
class Router {
  ocnstructor(options) {
    this.$optinos = options
    const initValue = window.location.hash.slice(1) || '/'
    Vue.util.defineReactive(this,'current',initValue)
    window.addEventListener('hashchange',()=> {
      this.current = window.location.hash.slice(1)
    })
  }
}
​
​
Router.install = function (_Vue) {
  Vue = _Vue
  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: {href: '#' + this.to}},this.$slot.default)
    }
  })
  Vue.component('router-view',{
    render(h) {
      let component = null
      const route = this.$router.$options.routes.find(route=> {
        route.path === this.current
      })
      if(route) {
        component = route.component
      }
      return h(component)
    }
  })
}

\