vue-router实现原理

164 阅读1分钟
  • 实现插件
  • url变化监听
  • 路由配置解析:{'/':Home}
  • 实现全局组件:router-link router-view
 class VueRouter{
     constructor(options){
         this.$options = options;
         this.routeMap = {};
         
         //路由响应式
         this.app = new Vue({
             data: {
                 current: "/"
             }
         })
     }
     
     init() {
         this.bindEvents() //监听url变化
         this.createRouteMap(this.$options);//解析路由配置
         this.initComponent();//实现两个组件
     }
     bindEvents() {
         window.addEventListener("load", this.onHashChange.bind(this)
         
         window.addEventListener('hashChange',this.onHashChange.bid(this))
     }
     
     onHashChange() {
         this.app.current = window.location.hash.slice(1) || '/'
     }
     
     createRouteMap(options){
         options.routes.forEach(item => {
         
             this.routeMap[item.path] = item.component;
             
         })
     }
     initComponent(){
         //router-link,router-view
         //<router-link to="">ffff</router-link>
         
         Vue.component("router-link",{
           props: {to:String},
           render(h){
               return h("a",{attrs: {href: '#' + this.to}},[this.$slot.default])
           }
         })
         
        // <router-view></router-view>
        Vue.component("router-view", {
          render: h => {
            const comp = this.routeMap[this.app.current];
            return h(comp);
} });
     }
     
 }
 
 VueRouter.install = function(vue){
     vue.mixin({
         beforeCreate() {
             //this是vue实例
             if(this.$options.router){
                 //仅在根组件执行一次
                 vue.prototype.$router= this.$options.router;
                 this.$options.router.init();
             }
         }
     })
 }