vue-router的原理

2,729 阅读4分钟

前端三大框架Vue,React,Angular,他们都是单页面应用开发的,所以利用路由的跳转非常有必要的,vue-router,react-router,angular-router都是基于前端路由原理进行封装实现的,所以我们使用起来非常方便,只会使用还不行,刚上手的小白,给他随便说两句就会使用路由,但是我们也需要了解路由的原理,知己知彼,才能百战百胜。

一、什么是路由

路由的概念起源于服务端,在以前前后端不分离的时候,由后端来控制路由,当接收到客户端发来的 HTTP 请求,就会根据所请求的相应 URL,来找到相应的映射函数,然后执行该函数,并将函数的返回值发送给客户端。他也存在这优势与劣势:

  • 优势: 安全性好,seo优化性能高
  • 劣势:加大服务器的压力,不利于用户体验。

所以前端路由才有了发展的空间。

前端路由的来源:

在很久很久以前~ 用户的每次更新操作都需要重新刷新页面,非常的影响交互体验,后来,为了解决这个问题,
便有了Ajax(异步加载方案),Ajax给体验带来了极大的提升。
虽然Ajax解决了用户交互时体验的痛点,但是多页面之间的跳转一样会有不好的体验,所以便有了
spa(single-page application)使用的诞生。而spa应用便是基于前端路由实现的,所以便有了前端路由。

如今比较火的vue-router/react-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()是修改了当前的历史记录项而不是新建一个。

onpopstate:

需要特别注意的是,调用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为例,看下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')

四、承上启下

上面我们已经了解了hash和history的原理,下面我们就来手写一把vue-router的源码。

可以看出来vue-router是通过Vue.use的方法被注入Vue实例中,在使用的时候我们需要全局用到vue-router的router-view和router-link,以及this.router/route 这样的实例对象。那么这些背后如何操作呢?

五、vue-router源码分析

下面就开始亲手开撸一个简单的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,分别是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的重新渲染。

参考:segmentfault.com/a/119000001…

juejin.cn/post/684490…