vue-router源码解析

2020-02-07  本文已影响0人  牛油果大虾
image.png

手写路由

class historyRoute{
            constructor(){
                this.current = null;
            }
        }

        class vueRouter{
            constructor(options){
                this.mode = options.mode||'hash'; 
                this.routes = options.routes||[];
                this.history = new historyRoute;
                this.routesMap = this.createMap(this.routes);
                this.init();
            }
            init(){
                if(this.mode === 'hash'){
                    location.hash?"":location.hash="/";
                    window.addEventListener('load',()=>{
                        this.history.current = location.hash.slice(1);
                    })
                    window.addEventListener('hashchange',()=>{
                        this.history.current = location.hash.slice(1);
                    })
                }else{
                    location.hash?"":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
                },{})
            }
        }
        vueRouter.install = function(Vue){
            Vue.mixin({
                beforeCreate(){
                    if(this.$options&&this.$options.router){
                        this._root = this;
                        this._router= this.$options.router;
                    }else{
                        this._root = this.$parent._root;
                    }
                }
            })
            Vue.util.defineReactive(this,'current',this._router.history);
            Vue.component('router-view',{
                render(h){
                    let current= this._self._root._router.history.current;
                    console.log(current);
                    let routesMap = this._self._root._router.routesMap;
                    console.log(reutesMap);
                    return h(routesMap[current]);
                }
            })
        }
        export default vueRouter;
上一篇下一篇

猜你喜欢

热点阅读