vue-router簡易的實現原理


 class VueRouter {
            constructor(options) {
                this.$options = options;
                this.routeMap = {};
                // 路由響應式
                this.app = new Vue({
                    data: {
                        current: "/"
                    }
                });
            }
            i
            nit() {
                this.bindEvents(); //監聽url變化
                this.createRouteMap(this.$options); //解析路由配置
                this.initComponent(); // 實現兩個組件
            }
            b
            indEvents() {
                window.addEventListener("load", this.onHashChange.bind(this));
                window.addEventListener("hashchange", this.onHashChange.bind(this));
            }
            o
            nHashChange() {
                this.app.current = window.location.hash.slice(1) || "/";
            }
            c
            reateRouteMap(options) {
                options.routes.forEach(item => {
                    this.routeMap[item.path] = item.component;
                });
            }
            i
            nitComponent() {
                // router-link,router-view
                // <router-link to="">fff</router-link>
                Vue.component("router-link", {
                    props: {
                        to: String
                    },
                    render(h) {
                        // h(tag, data, children)
                        return h("a", {
                            attrs: {
                                href: "#" + this.to
                            }
                        }, [
                            this.$slots.default
                        ]);
                    }
                });
                // <router-view></router-view>
                Vue.component("router-view", {
                    render: h => {
                        const comp = this.routeMap[this.app.current];
                        return h(comp);
                    }
                });
            }
        }
        V
        ueRouter.install = function (Vue) {
            // 混入
            Vue.mixin({
                beforeCreate() {
                    // this是Vue實例
                    if (this.$options.router) {
                        // 僅在根組件執行一次
                        Vue.prototype.$router = this.$options.router;
                        this.$options.router.init();
                    }
                }
            });
        };

以上是簡易的實現過程,一下是我整理了一份思路導圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM