simple vue-router

189 阅读1分钟
let Vue;
class Router{
    constructor(options) {
        //初始参数
        this.routeArr = options;
        //初始化路径
        let current = window.location.hash.slice(1) || "/"
        //使得routes可响应
        Vue.util.defineReactive(this,'routes', {path:current})
        //监听路由hash路由的变化
        window.addEventListener('hashchange',()=>{
          this.routes.path = window.location.hash.slice(1) || "/"
        })
    }
    //跳转路由push的方法
    push(path){
      window.location.href=`#${path}`;
    }
}

const install = (_Vue)=>{
  // 将路由实例都混入当中
  Vue = _Vue
  //将$router $route混入实例中
  Vue.mixin({
    beforeCreate(){
      if(this.$options.router){
         this.$router = this.$options.router;
         this.$routes = this.$options.router.routes;
      }else{
        this.$router = this.$parent && this.$parent.$router;
        this.$routes = this.$parent && this.$parent.$router.routes
      }
    }
  });
  // 创建router-view
  Vue.component('router-view',{
    render(h){
       let path = this.$routes.path;
       let component = this.$router.routeArr.routes.filter((value)=>value.path === path)[0].component || null;
       return h(component)
    },
  })
 //创建routerlink
 Vue.component('router-link', {
   props:{
     to:{
       type: String,
       required: true
     }
   },
   render(h){
    return h(
      'a',
      {
        attrs:{
          href:`#${this.to}`
        }
      },
      this.$slots.default
     )
   },
 })
}
export default {
  Router,
  install
}