Vue

Vue-router中hash模式和history模式

2020-01-15  本文已影响0人  冰雪_666
一、路由

1.前端路由

2.后端路由

3.前后端路由区别

二、hash模式和history模式的区别

1.hash

2.history

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '*', component: NotFoundComponent }
  ]
})
三、实现一个简单hash路由(没有支持子路由哦~)
class HistoryRoute{
    constructor(){
        this.current=null
    }
}
class vueRouter{
    constructor(options){
        this.mode=options.mode||'hash';
        this.routes=options.routes||[];
        this.routesMap=this.createMap(this.routes);
        this.history=new HistoryRoute;
        this.init();
    }
    init(){//获取当前current路径
        if(this.mode=='hash'){
            //自动加#
            location.hash?'':location.hash='/'
        }
        window.addEventListener('load',()=>{
            this.history.current=location.hash.slice(1)//获取#后面值
        })
        window.addEventListener('hashchange',()=>{//监听hash改变
            this.history.current=location.hash.slice(1)
        })
    }
        //将routes中路径和组件以键值对关联起来
    createMap(routes){
        return routes.reduce((memo,current)=>{
            memo[current.path]=current.component
            return memo
        },{})
    }
}
vueRouter.install=function(Vue){
    if(vueRouter.install.installed)return //判断插件是否已注册
    vueRouter.install.installed=true
    Vue.mixin({
        beforeCreate(){//实现双向数据绑定
            if(this.$options && this.$options.router){
                this._root=this
                this._router=this.$options.router;
                Vue.util.defineReactive(this,'current',this._router.history)
            }else{
                this._root=this.$parent._root
            }
            //$router不可修改
            Object.defineProperty(this,"$router",{
                get(){
                    return this._root._router;
                },
            })
            
        },
    })
    Vue.component('router-view',{//注册组件
        render(h){
            console.log(this._self)
            var current=this._self._root._router.history.current
            var routesMap=this._self._root._router.routesMap
            return h(routesMap[current])//渲染组件
        }
    })
}
export default vueRouter;
四、总结
上一篇 下一篇

猜你喜欢

热点阅读