前端学习笔记-vue-router

256 阅读1分钟
class HistoryRoute {
    constructor() {
        this.current = null
    }
}

class VueRouter {
    constructor(options) {
        this.mode = options.mode || 'hash';
        this.routes = options.routes || [];
        // 你传递的这个路由表示一个数组 
        // {'/home': Home, '/about', About}
        this.routesMap = this.createMap(this.routes);
        // console.log(this.routesMap);
        // 路由中需要存放当前的路径 需要状态
        this.history = new HistoryRoute;
        this.init();  //开始初始化操作
        
    }
    init() {
        if(this.mode === 'hash') {
            //先判断用户打开时有没有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.pathname ? '' : location.pathname = '/';
            window.addEventListener('load', ()=> {
                this.history.current = location.pathname
            })
            window.addEventListener('popstate', () => {
                this.history.current = location.pathname
            })
        }
    }
    createMap(routes) {
        return routes.reduce((memo, current) => {
            memo[current.path] = current.component
            return memo;
        }, {});
    }
}

// 使用vue.use 就会调用install方法
VueRouter.install = function(Vue, opts) {
    // 每个组件都有 this.$router / this.$route
    // 在所有组件中获取同一个路由的实例
    Vue.mixin({
        beforeCreate() {  //混合方法
            //获取组件的属性名字
            if(this.$options && this.$options.router) { // 定位根组件
                this._root = this; //把当前实例挂载在_root上
                this._router = this.$options.router //把router实例挂载在_router上
                // observer方法
                // 如果history中的current属性变化 也会刷新视图
                Vue.util.defineReactive(this,'_route', this._router.history)
            }
            else {
                // vue组件的渲染顺序 父 -> 子 -> 孙子
                this._root = this.$parent._root
            }

            // console.log('---------------',this.$options.name)
            Object.defineProperty(this,'$router', {    //Router的实例
                get() {
                    return this._root._router  //个人理解:把Router实例挂载到根组件_root上,在Vue.use(Router)(默认install)后,这样每个组件就都能获取到$router了!
                }
            })
            Object.defineProperty(this,'$route', {
                get() { // current属性

                    return {
                        //当前路由所在的状态
                        current: this._root._router.history.current
                    } 
                }
            })
        },
    })
    Vue.component('router-link', {
        props: {
            to:String
        },
        methods: {
            handleClick() {
                //如果是hash或history 怎么跳转
                alert(1)
            }
        },
        render(h) {
            let mode = this._self._root._router.mode
            let tag = this.tag
            // jsx 渲染
            return <tag on-click={this.handleClick} href={mode === 'hash' ? `#${this.to}` : this.to}>
                {this.$slots.default}</tag>
        },
    });
    Vue.component('router-view', { //根据当前的状态 current 路由表 {'/about' : About}
        render(h) {
            // 如何将current 表成动态的 current变化应该会影响视图刷新
            let current = this._self._root._router.history.current
            let routeMap = this._self._root._router.routesMap
            return h(routeMap[current])
        }
    });
}

export default VueRouter;