0
点赞
收藏
分享

微信扫一扫

Vue_Router底层封装

烟中雯城 2021-09-24 阅读 61
Vue

Vue_Router底层封装

let Vue;
class LxcRouter{
    //接收Vue.use传递过来的Vue
    static install(_Vue){
        Vue = _Vue;
    }
    constructor(options){
        //接收传递过来的配置项
        this.$options = options;
        //定义解析routes对象的变量
        this.routeMap = {};
        //定义路由的地址
        this.app = new Vue({
            data:{
                curr:"/"
            }
        })

      //调用初始化方法
      this.init();
    }
    init(){
        //1、绑定路由事件
        this.bindEvent();
        //2、创建路由对象
        this.createRouteMap()
        //3、创建组件
        this.createComponents();
    }
    bindEvent(){
        window.addEventListener("load",this.handleChange.bind(this));
        window.addEventListener("hashchange",this.handleChange.bind(this))
    }
    handleChange(){
        //更新视图
        var hash = this.getHash() || "/";
        this.app.curr = hash;
    }
    getHash(){
        return location.hash.slice(1);
    }
    createRouteMap(){
        this.$options.routes.forEach((item)=>{
            this.routeMap[item.path] = item;
        })

    }
    createComponents(){
        Vue.component("router-view",{
            render:h=>{
                var component = this.routeMap[this.app.curr].component;
                return h(component)
            }
        })

        Vue.component("router-link",{
            props:{
                to:{
                    type:String,
                    required:true
                }
            },
            render:function(h){
                return h("a",{
                    attrs:{
                        href:`#${this.to}`
                    }
                },
                this.$slots.default
                )
            }
        })
    }
}

export default LxcRouter;
举报

相关推荐

0 条评论