美文网首页
vue-router

vue-router

作者: 艾萨克菊花 | 来源:发表于2019-08-29 16:32 被阅读0次

    参考链接:

    https://www.jianshu.com/p/4295aec31302

    https://router.vuejs.org/zh/guide/

    一、vue router 原理

    vue-router通过 hashhistory interface 两种方式实现前端路由,更新视图但补充锌请求页面-是前端路由原理的核心之一,目前浏览器环境中这一功能的实现主要有两种方式:

    1、hash --- 利用 URL 中的 hash(‘#’)

    2、利用 History interface 在 HTML5 中新增的方法

    在 vue-router中,它提供 mode 参数来决定采用哪一种方式,选择流程如下:

    mode参数:

    - 默认 hash

    - histroy 注:如果浏览器不支持 history 新特性,则采用 hash 方式

    - 如果不在浏览器环境则使用 abstract(node环境下)

    mode

    区别:

    1、mode:‘hash’,多了‘#’

    http://localhost:8080/#/index

    2、mode:‘history’

    http://localhost:8080/index

    当选择 mode 类型之后,程序会根据你选择的 mode 类型创建不同的 history 对象(HashHistory/HTML5History/AbstractHistory)

    源码

    HashHistory

    1、HashHistory.push():将新路由添加到浏览器访问历史的栈顶

    push:入栈顶

    从设置路由改变到视图更新的流程:

    $router.push() --> HashHistory.push() --> Histroy.transitionTo() --> History.updateRoute() --> {app._route=route} --> vm.render()

    解析:

    1 $router.push() //调用方法

    2 HashHistory.push() //根据hash模式调用,设置hash并添加到浏览器历史记录(添加到栈顶)(window.location.hash= XXX)

    3 History.transitionTo() //监测更新,更新则调用History.updateRoute()

    4 History.updateRoute() //更新路由

    5 {app._route= route} //替换当前app路由

    6 vm.render() //更新视图

    2、HashHistory.replace()

    replace() 方法与 push() 方法不同之处在于,他并不是将新路由添加到浏览器访问历史的栈顶,而是替换掉当前的路由

    replace:直接替换

    replace (location: RawLocation, onComplete?: Function, onAbort?: Function) { this.transitionTo(location, route => { replaceHash(route.fullPath) onComplete && onComplete(route) }, onAbort)}

    function replaceHash (path) { const i = window.location.href.indexOf('#') window.location.replace( window.location.href.slice(0, i >= 0 ? i : 0) + '#' + path )}

    HTML5Histroy

    History interface 是浏览器历史记录栈提供的接口,通过 back() forward() go() 等方法,我们可以读取浏览器历史记录栈的信息,进行各种跳转操作。

    从 HTML5 开始 History interface 有进一步更新:pashState() replaceState() 这下不仅是读取了,还可以对浏览器历史记录栈进行更改:

    window.history.pushState(stateObject, title, URL)

    window.history.replaceState(stateObject, title, URL)

    - stateObject:当浏览器跳转到新的状态时,将触发 popState 时间,该事件将携带这个 stateObject 参数的副本

    - title:所添加记录的标题

    - URL:所添加记录的url

    1、push

    与 hash 模式类似,只是将 push 改为 history.pushState

    2、replace

    与 hash 模式类似,只是将window.replace改为history.replaceState

    3、监听地址变化

    在 HTML5History 的构造函数中监听popState(window.onpopstate)

    优缺点:(推荐使用 history模式)

    1、pushState() 设置的新 URL 可以是与当前 URL 同源的任意 URL;而 hash 只可以修改 # 后面的部分,故只可设置与当前同文档的URL

    2、pushState() 通过 stateObject 可以添加任意类型的数据到记录中;而 hash 只可以添加短字符串

    3、pushState() 可以额外设置 title 属性供后续使用

    4、history 模式则会将 URL 修改的就像正常请求后端的 URL 一样,如后端没有配置对应 /user/id 的路由处理,则会返回404错误

    二、

    相关文章

      网友评论

          本文标题:vue-router

          本文链接:https://www.haomeiwen.com/subject/srmmectx.html