简版vue-router,50行代码实现路由切换,组件注册

126 阅读1分钟
let Vue;
class Srouter {
  constructor(options) {
    this._options = options;
    //把current数据变成相应式
    Vue.util.defineReactive(
      this,
      "current",
      window.location.hash.slice(1) || "/"
    );
    window.addEventListener("hashchange", () => {
      this.current = window.location.hash.slice(1);
    });
  }
}
Srouter.install = function(_vue) {
  Vue = _vue;
  //mixin可延迟执行代码,Vue.use(router)在new Vue 前,固此时$options无值
  Vue.mixin({
    beforeCreate() {
      if (this.$options.router) {
        Vue.prototype.$router = this.$options.router;
      }
    },
  });
  //注册router-link组件
  Vue.component("router-link", {
    props: {
      to: {
        type: String,
      },
    },
    created() {},
    render(h) {
      return h("a", { attrs: { href: `#${this.to}` } }, this.$slots.default);
    },
  });
   //注册router-view组件
  Vue.component("router-view", {
    render(h) {
      let component = null;
      let obj = this.$router._options.routes.find(
        (item) => item.path === this.$router.current
      );
      if (obj) {
        component = obj.component;
      }
      return h(component);
    },
  });
};

export default Srouter;