Vue_Router底层封装

Vue_Router底层封装

关于Vue中的路由,做了底层的哈希路由的封装。基础路由相对容易,其中不足之处,慢慢再改进。后续会更新其他前后端路由的底层封装。

使用方式与Vue cli自动生成的路由基本相同,在router文件夹下的index.js文件中用import导入,取代原有插件中的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;

你可能感兴趣的:(Vue_Router底层封装)