vue-router的两种模式的区别

  

Vue Router 是一个官方的 Vue.js 路由管理器,它可以将组件与标识符映射为路由,然后将其传递给 Vue.js 实例进行渲染,在 Vue Router 中主要有两种路由模式:hash 模式和 history 模式。

hash 模式

hash 模式就是将路由信息放在 url 中的 hash (#)中,这种模式下的 url 格式为:

http://localhost:8080/#/home

在 Vue Router 中使用 hash 模式的代码如下:

const router = new VueRouter({
    mode: 'hash',
    routes: [
      {
        path: '/home',
        name: 'home',
        component: Home
      }
    ]
})

使用 hash 模式时,路由的变化不会导致浏览器向服务器发送请求,因为 hash 符号后面的内容是由浏览器自行解析的。并且 hash 模式下还可以根据 hashchange 事件进行路由的监听和切换。

history 模式

history 模式是使用 HTML5 的 history API 来实现 URI 与页面内容的映射关系,使用这种方式时,url 格式为:

http://localhost:8080/home

在 Vue Router 中使用 history 模式的代码如下:

const router = new VueRouter({
    mode: 'history',
    routes: [
      {
        path: '/home',
        name: 'home',
        component: Home
      }
    ]
})

相较于 hash 模式,history 模式更加简洁美观,但是要在服务器中进行相应的配置,否则在正常访问中会出现 404 错误,同时支持 history 模式的浏览器也有限。

示例:

在 hash 模式下,当我们从 /home 跳转到 /about 时,url 格式为:http://localhost:8080/#/about;而在 history 模式下,url 格式为:http://localhost:8080/about

// hash 模式下的代码示例
const router = new VueRouter({
    mode: 'hash',
    routes: [
      {
        path: '/home',
        name: 'home',
        component: Home
      },
      {
        path: '/about',
        name: 'about',
        component: About
      }
    ]
})

// history 模式下的代码示例
const router = new VueRouter({
    mode: 'history',
    routes: [
      {
        path: '/home',
        name: 'home',
        component: Home
      },
      {
        path: '/about',
        name: 'about',
        component: About
      }
    ]
})

总而言之,Vue Router 中的两种路由模式各有优缺点,我们可以根据具体业务场景来选择。

相关文章