您现在的位置是:群英 > 开发技术 > web开发
vue-roter的模式有哪些种?
Admin发表于 2022-09-16 17:55:41487 次浏览
今天这篇给大家分享的知识是“vue-roter的模式有哪些种?”,小编觉得挺不错的,对大家学习或是工作可能会有所帮助,对此分享发大家做个参考,希望这篇“vue-roter的模式有哪些种?”文章能帮助大家解决问题。

vue-roter有3种模式:1、hash模式,用URL hash值来做路由,支持所有浏览器;该模式实现的路由,在通过链接后面添加““#”+路由名字”。2、history模式,由h5提供的history对象实现,依赖H5 History API和服务器配置。3、abstract模式,支持所有JS运行环境,如Node服务器端,如果发现没有浏览器的API,路由会自动强制进入该模式。

如何快速入门VUE3.0:进入学习

本教程操作环境:windows7系统、vue3版,DELL G3电脑。

Vue-router 是vue框架的路由插件。

vue-roter有几种模式

根据vue-router官网,我们可以明确看到vue-router的mode值有3种

  • hash

  • history

  • abstract

其中,hash 和 history 是 SPA 单页应用程序的基础。

先说结论: spa应用路由有2种模式,hash 和 history,vue路由有3种模式,比 spa 多了一个 abstract。

源码分析

在vue-router中通过mode这个参数修改路由的模式:

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

具体怎么实现的呢,首先我们下载 vue-router 的源码

抽离出来对mode的处理

class vueRouter {
    constructor(options) {
        let mode = options.mode || 'hash'
        this.fallback =
        mode === 'history' && !supportsPushState && options.fallback !== false
        if (this.fallback) {
            mode = 'hash'
        }
        if (!inBrowser) {
            mode = 'abstract'
        }
        this.mode = mode

        switch (mode) {
            case 'history':
                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 !== 'production') {
                    assert(false, `invalid mode: ${mode}`)
                }
        }
    }
}

可以看到默认使用的是 hash 模式,当设置为 history 时,如果不支持 history 方法,也会强制使用 hash 模式。 当不在浏览器环境,比如 node 中时,直接强制使用 abstract 模式。

hash模式

阅读这部分源码前,我们先来了解下 hash 的基础: 根据MDN上的介绍,Location 接口的 hash 属性返回一个 USVString,其中会包含URL标识中的 '#' 和 后面URL片段标识符,'#' 和后面URL片段标识符被称为 hash。 它有这样一些特点:

  • 在第一个#后面出现的任何字符,都会被浏览器解读为位置标识符。这意味着,这些字符都不会被发送到服务器端。

  • 单单改变#后的部分,浏览器只会滚动到相应位置,不会重新加载网页。

  • 每一次改变#后的部分,都会在浏览器的访问历史中增加一个记录,使用"后退"按钮,就可以回到上一个位置。

  • 可通过window.location.hash属性读取 hash 值,并且 window.location.hash 这个属性可读可写。

  • 使用 window.addEventListener("hashchange", fun) 可以监听 hash 的变化

了解了这些基本知识后,我们继续来看 vue-router 源码对 /src/history/hash.js 的处理

    const handleRoutingEvent = () => {
      const current = this.current
      if (!ensureSlash()) {
        return
      }
      this.transitionTo(getHash(), route => {
        if (supportsScroll) {
          handleScroll(this.router, route, current, true)
        }
        if (!supportsPushState) {
          replaceHash(route.fullPath)
        }
      })
    }
    const eventType = supportsPushState ? 'popstate' : 'hashchange'
    window.addEventListener(
      eventType,
      handleRoutingEvent
    )
    this.listeners.push(() => {
      window.removeEventListener(eventType, handleRoutingEvent)
    })

首先也是使用 window.addEventListener("hashchange", fun) 监听路由的变化,然后使用 transitionTo 方法更新视图

  push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
    const { current: fromRoute } = this
    this.transitionTo(
      location,
      route => {
        pushHash(route.fullPath)
        handleScroll(this.router, route, fromRoute, false)
        onComplete && onComplete(route)
      },
      onAbort
    )
  }

  replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {
    const { current: fromRoute } = this
    this.transitionTo(
      location,
      route => {
        replaceHash(route.fullPath)
        handleScroll(this.router, route, fromRoute, false)
        onComplete && onComplete(route)
      },
      onAbort
    )
  }

vue-router 的2个主要API push 和 replace 也是简单处理了下 hash , 然后调用 transitionTo 方法更新视图

history模式

老规矩,先来了解下 HTML5History 的的基本知识: 根据MDN上的介绍,History 接口允许操作浏览器的曾经在标签页或者框架里访问的会话历史记录。 使用 back(), forward()和 go() 方法来完成在用户历史记录中向后和向前的跳转。 HTML5引入了 history.pushState() 和 history.replaceState() 方法,它们分别可以添加和修改历史记录条目。 稍微了解下 history.pushState():

window.onpopstate = function(e) {
   alert(2);
}

let stateObj = {
    foo: "bar",
};

history.pushState(stateObj, "page 2", "bar.html");

这将使浏览器地址栏显示为 mozilla.org/bar.html ,但并不会导致浏览器加载 bar.html ,甚至不会检查bar.html 是否存在。 也就是说,虽然浏览器 URL 改变了,但不会立即重新向服务端发送请求,这也是 spa应用 更新视图但不 重新请求页面的基础。 接着我们继续看 vue-router 源码对 /src/history/html5.js 的处理:

    const handleRoutingEvent = () => {
      const current = this.current

      // Avoiding first `popstate` event dispatched in some browsers but first
      // history route not updated since async guard at the same time.
      const location = getLocation(this.base)
      if (this.current === START && location === this._startLocation) {
        return
      }

      this.transitionTo(location, route => {
        if (supportsScroll) {
          handleScroll(router, route, current, true)
        }
      })
    }
    window.addEventListener('popstate', handleRoutingEvent)
    this.listeners.push(() => {
      window.removeEventListener('popstate', handleRoutingEvent)
    })

处理逻辑和 hash 相似,使用 window.addEventListener("popstate", fun) 监听路由的变化,然后使用 transitionTo 方法更新视图。 push 和 replace 等方法就不再详细介绍。

abstract模式

最后我们直接来看一下对 /src/history/abstract.js 的处理:

  constructor (router: Router, base: ?string) {
    super(router, base)
    this.stack = []
    this.index = -1
  }

首先定义了2个变量,stack 来记录调用的记录, index 记录当前的指针位置

  push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
    this.transitionTo(
      location,
      route => {
        this.stack = this.stack.slice(0, this.index + 1).concat(route)
        this.index++
        onComplete && onComplete(route)
      },
      onAbort
    )
  }

  replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {
    this.transitionTo(
      location,
      route => {
        this.stack = this.stack.slice(0, this.index).concat(route)
        onComplete && onComplete(route)
      },
      onAbort
    )
  }

push 和 replac方法 也是通过 stack 和 index 2个变量,模拟出浏览器的历史调用记录。

总结

终于到了最后的总结阶段了:

  • hash 和 history 的使用方式差不多,hash 中路由带 # ,但是使用简单,不需要服务端配合,站在技术角度讲,这个是配置最简单的模式,本人感觉这也是 hash 被设为默认模式的原因

  • history 模式需要服务端配合处理404的情况,但是路由中不带 # ,比 hash 美观一点。

  • abstract 模式支持所有JavaScript运行环境,如Node.js服务器端,如果发现没有浏览器的API,路由会自动强制进入这个模式。

    abstract 模式没有使用浏览器api,可以放到node环境或者桌面应用中,是对 spa应用 的兜底和能力扩展。


以上就是关于“vue-roter的模式有哪些种?”的介绍了,感谢各位的阅读,希望文本对大家有所帮助。如果想要了解更多知识,欢迎关注群英网络,小编每天都会为大家更新不同的知识。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

标签: vue-roter
相关信息推荐
2022-05-16 11:37:25 
摘要:HTML5新增的标签:canvas、audio、video、source、embed、track、datalist、keygen、output、article、aside、bdi、nav、mark、rt、rp、ruby、time、wbr等。
2022-12-09 17:50:23 
摘要:4种方法:1、用ltrim()去除字符串左侧的回车符,语法“ltrim(字符串)”;2、用rtrim()去除字符串右侧的回车符,语法“rtrim(字符串)”;3、用trim()去除字符串两侧的回车符,语法“trim(字符串)”;4、用preg_replace()配合正则表达式来去除全部回车符,语法“preg_replace('/\r|\n/','',字符串)”。
2021-11-18 19:04:33 
摘要:验证码相信大家都不陌生,比较常见的有一般数字字母验证码、有干扰素的数字字母验证码、图片验证码等等,这篇我们我们来了解如何用PHP和GD哭实现有干扰素的验证码功能,文中示例代码介绍的非常详细,感兴趣的朋友接下来一起跟随小编看看吧。
云活动
推荐内容
热门关键词
热门信息
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部