第二章-路由模式

77 阅读1分钟

路由模式

vue2安装使用的是vue-router@3

vue3安装使用的是vue-router@4

vue-router@3和vuerouter@4的区别

  • vue-router@3 通过mode设置路由模式
    const router = new VueRouter({
        routes: [],
        mode: 'history | hash | abstact'
    })
    
  • vue-router@4 通过history设置路由模式
    const router = createRouter({
        routes: [],
        history: createWebHistory() | createWebHashHistory() | createWebMemoryHistory()
    })
    

路由模式的区别

  1. hash模式

    hash跳转页面是通过window.location.hash(path)方式实现的。

    hash 模式 下,url地址栏会以#开头,hash是URL中hash(#)及后面的部分,常用作锚点在页面内进行导航。

    改变URL中的hash部分不会引起页面刷新。

    通过hashchange事件监听URL的变化,改变URL的方式只有这几种:

    • 通过浏览器前进后退改变URL
    • 通过<a>标签改变URL
    • 通过window.location改变URL

    image.png

  2. history模式

    基于h5的history去实现的

    history提供了 pushStatereplaceState 两个方法,这两个方法改变 URL 的path部分不会引起页面刷新

    history提供了类似hashchange事件的popstate事件,但popstate事件有些不同:

    • 通过浏览器前进后退改变URL时会触发opstate事件
    • 通过pushState/replaceState或<a>标签改变URL不会触发popstate事件
    • 但是我们可以拦截psuhState/replaceState的调用和<a>标签的点击事件来监测URL变化
    • 通过js的history的back、go、forward方法会触发popstate事件 所以监听URL变化可以实现,只是没有hashchange方便

    image.png