vue router实现的源码

// 创建一个全局变量,用来保存vue的构造函数
    let vue;

    class KVueRouter{
        constructor(options){
            this.$options = options;


        }
    }

    // 1.实现插件
    // 在使用插件时,会把vue的构造函数当成参数传进来
    KVueRouter.install = function(_vue){
        Vue = _vue; //保存构造函数,在KVueRoutero里面使用

        // 使用mixin获取根实例上的router选项
        Vue.mixin({
            beforeCreate() {
                console.log(this);
                // 确保根实例时,才执行挂载
                if(this.$options.router){
                    Vue.prototype.$router = this.$options.router;
                }
            }
        })


        // 2.实现router-link组件
        Vue.component('router-link',{
            props:{
                to:{
                    required:true
                }
            },
            // 不能使用template来,因为不能在只有运行时版本时候使用template,而是使用render
            render(h){
                // <a href='#/about'>关于</a>
                let path = ''
                if(typeof this.to === 'string'){
                    path = this.to
                }else if(typeof this.to === 'object'){
                    path = '/'+this.to.name
                }
                console.log(this.$slots); //当前组件的插槽集合,default:[Vnode]为其默认插槽内容
                return h('a',{attrs:{href:'#' + path}},this.$slots.default) //里面的内容使用一个匿名插槽
            }
        })

        // 3.实现router-view组件
        Vue.component('router-view',{
            render(h){
                const {routeMap,curPath} = this.$router; //获取路由映射表,和当前路由值
                let component = routeMap[curPath] || null
                return h(component)
            }
        })

    }

    export default KVueRouter;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值