vue-router原理解析

“更新视图但不重新请求页面”是前端路由原理的核心之一,

一 主要有两种模式hash模式和history模式。

1.hash模式

URL的hash 是以#开头,是基于location.hash来实现的。
Location.hash的值就是URL中#后面的内容。当hash改变时,页面不会因此刷新,浏览器也不会请求服务器。

同时,hash 改变时,并会出发相应的hashchange事件,所以,hash很适合被用来做前端路由。当hash路由发生跳转,便会触发hashchange回调,回调里面就可以实现页面的更新操作,从而达到跳转页面的效果。

   // 当Html文档加载完毕后,会触发load事件 
    window.addEventListener("load",()=>{
        // 在浏览器中有一个api叫location 
        console.log(location.hash)
        // location是浏览器自带   也就是说是Hash路由的原理是location.hash 
        box.innerHTML = location.hash.slice(1)  //slice把前一个字符串去掉
    })
    // hashchange  当hash改变时触发这个事件 
    window.addEventListener("hashchange",()=>{
        box.innerHTML = location.hash.slice(1)
    })

2.history模式

主要是HTML5的History API 为浏览器的全局history对象增加的扩展方法。

pushState

需要三个参数:一个状态对象, 一个标题(目前被忽略), 和一个URL

  • state, 状态对象state是一个JavaScript对象,popstate事件触发时,该对象会传入回调函数
    title, 目前所有浏览器忽略
    url, 新的url记录

replaceState

history.replaceState()的使用与history.pushState()非常相似,区别在于replaceState()是修改了当前的历史记录项而不是新建一个。

popstate

需要特别注意的是,调用history.pushState()或history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,比如点击后退、前进按钮【或者调用JS中的history.back()、history.forward()、history.go()】才会触发该事件。

如果当前处于激活状态的历史记录条目是由history.pushState()方法创建,则popstate事件对象的state属性包含了这个历史记录条目的state对象的一个拷贝。

history.pushState({},null,pathname)
//使用popstate事件来监听url的变化
window.addEventListener("popstate",()=>{
        console.log(location.pathname)
        go(location.pathname)
    })

二 vue中路由的实现

vue中使用路由

router.js:
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [...]
})

main.js:
import router from './router'
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

下面就开始亲手开撸一个简单的vue-router:

第一步: install方法

可以创建一个Vue项目,将router中的路由信息抽离出来,主要的源码在vue-router中。当Vue.use(vueRouter)时候,就会调用vue-router中的install方法

通过Vue.mixin()方法,全局注册一个混合,影响注册之后所有创建的每个 Vue 实例,该混合在beforeCreate钩子中通过Vue.util.defineReactive()定义了响应式的_route属性。所谓响应式属性,即当_route值改变时,会自动调用Vue实例的render()方法,更新视图。

Vue.mixin({  //mixin 混入 
        beforeCreate() {
            // console.log(this.$options);  //每一个vue组件  
            // console.log(this.$options);
            //获取根组件  因为根组件下面 有router
            if (this.$options && this.$options.router) {
                // 找到根组件
                // 把当前实例挂载到_root上
                // console.log(this);
                // 把router实例挂载到_router上面
                this._router = this.$options.router
                this._root = this  // main 根组件
                //监控路径的变化 为了让 _router 的变化能及时响应页面的更新,所以又接着又调用了 Vue.uti.defineReactive方法来进行get和set的响应式数据定义。
                Vue.util.defineReactive(this, "xxx", this._router, history)
            } else {
                // console.log(this); //app组件
                this._root = this.$parent._root;
            }
            Object.defineProperty(this, "$router", {
                get() {
                    return this._root._router
                },
                push(){

                }
            })
            Object.defineProperty(this, "$route", {
                get() {
                    return {
                        current: this._root._router.history.current
                    }
                }
            })
        }
    }),

第二步: crateMap转换路由格式

将路由信息转换格式,利用createmap转换路由信息格式。

createMap(routes) {
        return routes.reduce((memo, current) => {
            //meomo刚开始是一个空对象
            memo[current.path] = current.component;
            return memo;
        }, {})
    }

第三步: 创建VueRouter类,初始化mode routes routesMap对象

在路由里面new了,说明 vue-router中是一个类,此时 ,将new中的对象options 传到VueRouter类中。将mode routes routesMap history挂载到VueRouter上,并使用了init方法。

class HistoryRoute {
    constructor() {
        this.current = null;
    }
}
 constructor(options) {
        // console.log(options);
        this.mode = options.mode || "hash";
        this.routes = options.routes || [];
        this.routesMap = this.createMap(this.routes);
        this.history = new HistoryRoute();
        this.init();
    }

第四步: hash 和history

在constructor中使用this.init()方法,在init方法里面可以判断路由的mode是hash还是 history。

  init() {
        if (this.mode === "hash") {
            location.hash ? "" : location.hash = "/";  //#/会加上了 
            // console.log(location.hash);
            window.addEventListener("load", () => {
                this.history.current = location.hash.slice(1)
                // console.log("load-->", this.history.current)
            })
            window.addEventListener("hashchange", () => {
                this.history.current = location.hash.slice(1)
                // console.log("hashchange-->", this.history.current)
            })

        } else {
            //使用history
            // console.log("History");
            location.pathname ? "" : location.pathname = "/";
            window.addEventListener("load", () => {
                this.history.current = location.pathname
                // console.log("load--->", this.history.current)
            })
            window.addEventListener("popstate", () => {
                this.history.current = location.pathname
                // console.log("popstate--->", this.history.current)
            })
        }
    }
    // 把方法写到$router上去
    push() { }
    go() { }
    back() { }

原理总结

通常构建一个Vue应用的时候, 我们会使用Vue.use以插件的形式安装VueRouter。同时会在Vue的实例上挂载router的实例。在vueRouter这个插件中有一个公共的方法install,这个方法的第一个参数是Vue构造器,第二个参数是一个可选的参数对象,其中在install文件中,并且混入了mixin,给每一个组件创建beforeCreate钩子,在Vue的实例上初始化了一些私有属性,其中_router指向了VueRouter的实例,_root指向了Vue的实例。

在Vue中利用数据劫持defineProperty在原型prototype上初始化了一些getter,分别是r o u t e r 代 表 当 前 R o u t e r 的 实 例 、 router 代表当前Router的实例、router代表当前Router的实例、route 代表当前Router的信息。在install中也全局注册了router-view,router-link,其中的Vue.util.defineReactive, 这是Vue里面观察者劫持数据的方法,劫持_route,当_route触发setter方法的时候,则会通知到依赖的组件。

接下来在init中,会挂载判断是路由的模式,是history或者是hash,点击行为按钮,调用hashchange或者popstate的同时更新_route,_route的更新会触发route-view的重新渲染。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值