实现vue-router

实现vue-router,第1张

let Vue
class VueRouter{
    constructor(options){
        //this.current = "/" //当前路由
        let initPath = "/" //默认路由
        Vue.util.defineReactive(this,"current",initPath) //util里有vue封装的一些方法,其中defineReactive相当于object.defineProperty,第一个参数是对象,第二个是属性,第三个是属性值 ,在这里用这个,是为了让current实现响应式。因为url地址是会变的,变了后,router-view组件要判断current属性值,然后渲染相应组件。
        this.routes = options.routes //用户的路由规则
        this.mode =options.mode || "hash"
        this.init() //监听路由改变
    }
    init(){
        if(this.mode === "hash"){
            console.log(location.hash)    // 打印出来是"#/"
            //注意第一次加载项目,去除#
            window.addEventListener("load",()=>{
                this.current = location.hash.slice(1)
            })
            //路由地址改变监听,去除#
            window.addEventListener("hashchange",()=>{
                this.current = location.hash.slice(1)
            })
        }
    }
}
//插件机制
VueRouter.install = function(_Vue){
    Vue = _Vue
    //给调用的组件添加一个属性 router
    Vue.mixin({ //全局添加数据和方法
        beforeCreate(){
            if(this.$options.router){  //每个vue实例都有自己的options,这里是配置根实例,在main.js中 new的时候,有router,为了每个实例都有router.
                Vue.protoType.$router = this.$options.router
            }
        }
    })
    //全局组件,用
    //router-link 
    Vue.component("router-link",{
        props:{
            to:{   //获取组件to属性的值,也就是跳转的目标地址
                type:String,
                require:true
            }
        },
        render(h){
            return h('a',{attrs:{
                href:"#" + this.to
            }},this.$slots.default)   
            //home
            // h函数用来创建html标签,router-link相当于a标签,this.$slots.default是组件插槽传的值
        }
    })
    //router-view 
    Vue.component("router-view",{
        render(h){  
            //当前的路由地址 + 路由规则,判断当前地址是否与router里的path中的每一项是否一致,一致则把组件渲染出去。
            let current = this.$router.current
            let routes = this.$router
            let com = routes.find(item =>{
                return current === item.path
            })
            return h(com.component)   //h函数用来创建html标签,router-view相当于div标签
        }
    })
}

export default VueRouter

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1324673.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存