實(shí)現(xiàn)一個簡單地vueRouter

import Vue from 'vue'
export default class vueRouter{ // 聲明一個vueRouter類
  constructor (options){ // 參數(shù)就是你傳進(jìn)來的路由對象
    this.$options = options;
    this.routerMap = {};
    this.app = new Vue({// 主要是利用vue的響應(yīng)式原理
      data:{ // 這兩種方法都可以
        current:'/'
      }
      // data () { // data在組件里使用必須是一個函數(shù)  因?yàn)榻M件可以會生成多個實(shí)例 如果data仍然是一個純粹的對象,則所有的實(shí)例將共享引用同一個數(shù)據(jù)對象
      //   return{
      //     current:'/'
      //   }
      // }
    })
  }
  init () {
    this.bindEvents();// 監(jiān)聽事件
    this.createRouteMap(); // 解析路由
    this.initComponet(); //實(shí)現(xiàn)組件
  }
  bindEvents (){
    window.addEventListener('load',this.onHashChange.bind(this));//load時觸發(fā)
    window.addEventListener('hashchange',this.onHashChange.bind(this));// 錨發(fā)生變化觸發(fā)也就是#后面發(fā)生變化
  }
  onHashChange () {
    this.app.current = window.location.hash.slice(1) || '/'
  }
  createRouteMap (){
    this.$options.routes.forEach(item =>{
      this.routerMap[item.path] = item.component;
    })
  }
  initComponet (){
    // router link
    Vue.component('router-link',{
      props:{to:String},
      render(h) {
        return h('a',{attrs:{href:'#'+this.to}},[this.$slots.default])
      }
    })
    // router view
    Vue.component('router-view',{
      render:(h)=>{
        const comp = this.routerMap[this.app.current] // this.app.current 發(fā)生變化 組件就會發(fā)生變化
        return h(comp)
      }
    })
  }
}
vueRouter.install = function(Vue){ //聲明一個install方法 這個方法接受一個vue實(shí)例
  Vue.mixin({ // 混入
    beforeCreate() { // 所有組件的這個生命周期鉤子 執(zhí)行的時候
      if(this.$options.router){ // 組件如果有這個router
        Vue.prototype.$router = this.$options.router
        this.$options.router.init(); //執(zhí)行初始化方法
      }
    }
  })

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容