浅析vue-router中history模式

浅析vue-router中history模式

之前的学习中写过一篇有关vue-router中hash模式的一点思考现在呢有时间就打算把history模式的源码也看一看学习一下。然后写一下自己对于history模式的理解。

路由初始化

本次学习使用的是vue-router v3.0.2版本源码进行。对于前端路由主要就是解决了改变浏览器url输入框中的值,可以在不整体刷新页面的情况下动态的改变页面中的显示的内容,即可以部分刷新页面。这也是SPA应用的一个基本述求。相较于MPA应用每次都会重新获取不同的html文档是一种全新不同的使用体验。
在vue-router中更是使用不同的模式来实现这一述求:

  • hash模式
  • history模式
  • abstract模式

本次学习的目标主要是history模式下vue-router的工作原理。

// index.js主要代码 代码类型检测使用的flow
export default class VueRouter {
   
  // 省略了部分类中的属性
  constructor (options: RouterOptions = {
   }) {
   
    this.app = null
    this.apps = []
    this.options = options
    this.beforeHooks = []
    this.resolveHooks = []
    this.afterHooks = []
    this.matcher = createMatcher(options.routes || [], this)
    // mode由初始化时传入的mode初次决定
    let mode = options.mode || 'hash'
    // 是否回退的flag,此处supportsPushState检测了浏览器是否支持h5的history api
    this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false
    if (this.fallback) {
   
      mode = 'hash'
    }
    if (!inBrowser) {
   
      mode = 'abstract'
    }
    this.mode = mode
    // 此处进入router的最终初始化
    switch (mode) {
   
      case 'history':
        // 传入router自身,及options的base选项
        this.history = new HTML5History(this, options.base)
        break
      case 'hash':
        this.history = new HashHistory(this, options.base, this.fallback)
        break
      case 'abstract':
        this.history = new AbstractHistory(this, options.base)
        break
      default:
        if (process.env.NODE_ENV !=&#
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值