vue-router的实现原理

99 阅读1分钟

引言

首先引入vue-router,然后使用Vue.use(VueRouter)注册插件,然后new VueRouter传入参数,这两个操作可以看出导出的内容是一个类,并且类有一个静态属性install

代码

    let Vue=null
    class VueRouter{
        static install=function(_Vue){
            Vue=_Vue
            Vue.mixin({
                beforeCreate(){
                    if(this.$options.router){
                        this.$router=this.$options.router
                    }else if(this.$parent){
                         this.$router=this.$parent.$router
                    }
                }
            })
            //添加全局组件router-link,router-view
            Vue.component("router-link",{
                props:{
                    to:{
                        type:String,
                        required:true
                    }
                }
                render:h=>h('a',{
                    href:"#"+this.to
                },this.$slots.default)
            })
            Vue.component("router-view",{ 
                render:h=>h(this.$router.routesMap[this.$router._router])
            })
        }
        constructor(options){
            let {routes}=options
           this. routesMap={}
            routes.forEach(item=>{
                this.routesMap[item.path]=item.component
            )
            Vue.util.defineReactive(this,_router,"/    ")
            location.hash=location.hash||"#/"
            this._router=location.hash.slice(1)
            window.addEventListener("load",()=>{
             location.hash=location.hash||"#/"
                this._router=location.hash.slice(1)
            })
            window.addEventListener("hashchange",()=>{
                 location.hash=location.hash||"#/"
                this._router=location.hash.slice(1)
            })
        }
        
    }

export default VueRouter