美文网首页
vue-router源码解析

vue-router源码解析

作者: 牛油果大虾 | 来源:发表于2020-02-07 13:45 被阅读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;
    

    相关文章

      网友评论

          本文标题:vue-router源码解析

          本文链接:https://www.haomeiwen.com/subject/mtpmxhtx.html