手寫vueRouter-Hash模式

ZhandsomeZ發表於2020-12-13

在這裡插入圖片描述

前言
本篇文章主要是給大家帶來vueRouter-Hash模式的手動實現
程式碼實現
let _Vue = null
export default class VueRouter {
    static install(Vue) {
        if (VueRouter.install.installed) {
            return
        }
        VueRouter.install.installed = true
        _Vue = Vue
        _Vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router;
                    this.$options.router.init();
                }
            }
        })
    }
    constructor(options) {
        this.options = options
        this.routeMap = {};
        this.data = _Vue.observable({
            current: '/#/',
        })
    }
    init() {
        this.createRouteMap();
        this.initComponents(_Vue);
        this.initEvent()
    }
    createRouteMap() {
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component
        })
    }
    initComponents(Vue) {
        const self = this
        Vue.component('router-link', {
            props: {
                to: String
            },
            render(h) {
                return h('a', {
                    attrs: {
                        href: this.to,
                    },
                    on: {
                        click: this.clickHandler,
                    }
                }, [this.$slots.default])
            },
            methods: {
                clickHandler(e) {
                    location.hash = this.to
                    this.$router.data.current = this.to
                    e.preventDefault();
                }
            },
        },
        )
        Vue.component('router-view', {
            render(h) {
                const component = self.routeMap[self.data.current]
                return h(component)
            }
        })
    }
    initEvent() {
        window.addEventListener('onhashchange', () => {
            this.data.current = window.location.hash
        })
    }

}

謝謝觀看,如有不足,敬請指教