06【手写vue-router】实现router-view

原理:根据路由取到要展示的组件,然后用render函数进行渲染。

myRouter.install = (Vue, options)=>{
    Vue.mixin({
        beforeCreate(){
            if(this.$options && this.$options.router){
                this.$router = this.$options.router;
                this.$route = this.$router.routeInfo;
            // 先渲染组件再执行onload事件,所以拿不到currentPath,所以用vue的响应式方法去观测路由的变化
                Vue.util.defineReactive(this, 'xxx', this.$router);
            }else{
                this.$router = this.$parent.$router;
                this.$route = this.$router.routeInfo;
            }
        }
    });
    /*
    只要外界使用了Vue-Router, 那么我们就必须提供两个自定义的组件给外界使用
    只要外界通过Vue.use注册了Vue-Router, 就代表外界使用了Vue-Router
    只要接通通过Vue.use注册了Vue-Router, 就会调用插件的install方法
    所以我们只需要在install方法中注册两个全局组件给外界使用即可
    * */
    Vue.component('router-link', {
        props: {
            to: String
        },
        render(){
            /*
            注意点: render方法中的this并不是当前实例对象, 而是一个代理对象
                    如果我们想拿到当前实例对象, 那么可以通过this._self获取
            * */
            // console.log(this._self.$router.mode);
            let path = this.to;
            if(this._self.$router.mode === 'hash'){
                path = '#' + path;
            }
            return <a href={path}>{this.$slots.default}</a>
        }
    });
    Vue.component('router-view', {
        render(h){
            // console.log('render');
            let routesMap = this._self.$router.routesMap;
            let currentPath = this._self.$route.currentPath;
            // console.log(currentPath);
            let currentComponent = routesMap[currentPath];
            return h(currentComponent);
        }
    });
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,535评论 1 33
  • 回忆: 我们知道,h5的history或者hash帮助我们解决了,变化url跳转页面不发送请求,并且我们能监听到u...
    LoveBugs_King阅读 3,682评论 0 5
  • 这是一篇集合了从如何查看 vue-router源码(v3.1.3),到 vue-router源码解析,以及扩展了相...
    尤小小阅读 5,633评论 2 14
  • 渲染函数和jsx 在vue中我们可以不用template来指定组件的模板,而是用render函数来创建虚拟dom结...
    6e5e50574d74阅读 732评论 0 0
  • [toc] REACT react :1.用来构建用户界面的 JAVASCRIPT 库2.react 专注于视图层...
    拨开云雾0521阅读 1,495评论 0 1