SOURCE

class HistoryRouter {
    constructor(){
        this.current = null
    }
}

class VueRouter {
    constructor(options){
        this.$options = options
        this.routes = options.routes || []
        this.mode = options.mode || 'hash'
        this.history = new HistoryRouter()
        this.routesMap = this.createMap(this.routes) // [{},{}]变成}{path:component}
        this.init()
    }
    init(){
        if(this.mode === 'hash'){
            // 自动加# location.hash赋值/浏览器会自动加#
            window.location.hash ? '' : window.location.hash='/'

            window.addEventListener('load',()=>{
                this.history.current = location.hash.slice(1)
            })
            window.addEventListener('hashchange',()=>{
                this.history.current = location.hash.slice(1)
            })
        }
    }
    createMap(routes){
        return routes.reduce((memo,current)=>{
            memo[current.path] = current.component
            return memo
        },{})
    }
}

VueRouter.install = function(vue){
    // 写插件注意要判断插件是否已经注册
    if(VueRouter.install.installed) return false
    VueRouter.install.installed = true
    Vue.mixin({
        beforeCreate(){
            if(this.$options && this.$options.router){
                this._root = this
                this._router = this.$options.router
                Vue.util.defineReactive(this,'current',this._router.history)
            }else{
                this._root = this.$parent._root
            }
        }
    })
    Vue.component('router-view',{
        render(h){
            let current = this._self._root._router_history.current
            let routerMap = this._self._root._router.routesMap
            return h(routerMap[current])
        }
    })
}

export default VueRouter
console 命令行工具 X clear

                    
>
console