vue-router源码抽离简单剖析

230 阅读1分钟
/**
 * vue-router源码抽离简单剖析
 */

let _Vue;

/**
 * 创建HTML5History构造函数 为History模式下使用
 */
class HTML5History {
    constructor (route, base) {
        // 记录当前路由状态
        this.current = '';
        // 借用new _Vue 中data的响应特性数据 创建可响应的 app
        this.app = new _Vue({
            data() {
                return {
                    path: '/'
                }
            },
        })
    }
    /**
     * 利用浏览器的browserHistory原理
     * 添加popstate监听,可以监听到浏览器前进、后退。
     * 但不能监听到pushState、replaceState,
     * 所以在执行pushState、replaceState的时候进行页面更换 this.app.path = this.current
     */
    setupListeners() {
        const handleRoutingEvent = () => {
            this.current = location.pathname?.slice(1) || '/';
            this.app.path = this.current;
        }
        window.addEventListener(
            'popstate',
            handleRoutingEvent
        )
    }
    // 创建一个 push方法 修改 当前路由位置
    push (path) {
        history.pushState({}, '', path);
        this.app.path = path;
    }
}
/**
 * 创建HashHistory构造函数 为hash模式下使用
 * 
 * 使用锚点,hashHistory
 */
class HashHistory {
    constructor (route, base) {
        this.current = '';
        this.app = new _Vue({
            data() {
                return {
                    path: '/'
                }
            },
        })
    }

    // 添加hashchange监听 获取hash变化 触发页面更换
    setupListeners() {
        const handleRoutingEvent = () => {
            this.current = location.hash?.slice(1) || '/';
            this.app.path = this.current;
        }
        window.addEventListener(
            'hashchange',
            handleRoutingEvent
        )
    }
    // 创建一个 push方法 修改 当前hash值
    push (location) {
        window.location.hash = location
    }
}

// 创建Router构造函数 用于处理当前路由创建信息
class Router {
    // 创建是记录所有options 项目中常用的routes树
    constructor(options) {
        this.options = options;
        // 默认hash模式  仅 history  hash 两种模式
        let mode = options.mode || 'hash';
        this.routes = options.routes;
        switch (mode) {
            case 'history':
              this.history = new HTML5History(this, options.base)
              break
            case 'hash':
              this.history = new HashHistory(this, options.base, this.fallback)
              break
            default:
              // 报错
          }
    }
    // 初始化绑定 对应的监听
    init() {
        this.history.setupListeners()
    }
    // 创建对应push方法
    push (location) {
        this.history.push(location)
    }
}

/**
 * Vue.use() 时调用 此注册函数
 */
Router.install = function(Vue) {
    // 缓存备用
    _Vue = Vue;
    // 通过mixin混入 创建实例时挂载到当前组件
    Vue.mixin({
        beforeCreate () {
            // 获取到当前页面的router信息
            if (this.$options.router) {
                this._routerRoot = this
                this._router = this.$options.router
                this._router.init(this)
            } else {
                this._routerRoot = (this.$parent && this.$parent._routerRoot) || this
            }
        }
    })
    // 劫持Vue.prototype.$router 动态绑定get订阅函数
    Object.defineProperty(Vue.prototype, '$router', {
        get () { return this._routerRoot._router }
    })
    // 劫持Vue.prototype.$route 动态绑定get订阅函数
    Object.defineProperty(Vue.prototype, '$route', {
        get () { return this._routerRoot._route }
    })

    // 创建router-view组件 进行render 找到对应的component组件渲染
    Vue.component('router-view',{
        render(h){
            const path = this._routerRoot._router.history.app.path;
            const routes = this._routerRoot._router.routes;
            const route = routes.find((i) => i.path === `/${path}`)
            const com = route ? route.component : routes.find((i) => i.path === `/404`).component
            return h(com)
        }
    })
    
}
// 导出Router函数 供使用
export default Router;

参考文章 history vue-router