vue-router两种模式区别及使用注意事项详解

  

Vue-router两种模式区别及使用注意事项详解

前言

在学习Vue时,经常会使用Vue-router来实现前端路由。Vue-router有两种模式:history模式和hash模式。本篇文章将详细讲解这两种模式的区别,并给出使用注意事项。

区别

Hash模式

默认模式是hash模式,即地址栏的URL格式是以#/开头,比如:

http://localhost:8080/#/home

在hash模式下,当URL发生变化时,页面不会重新加载,而是通过捕获hash变化事件来进行局部更新。

在Vue-router中,通过mode: 'hash'来指定使用hash模式。

History模式

另一种模式是history模式,即地址栏的URL格式是普通的URL格式,比如:

http://localhost:8080/home

在history模式下,当URL发生变化时,页面会走正常的HTTP请求流程,因此在使用history模式时,需要保证服务器正确配置,以免出现404错误。

在Vue-router中,通过mode: 'history'来指定使用history模式。

注意事项

Hash模式下的路由传参

在hash模式下的路由传参,使用$route.query方式是无效的,应该使用$route.params。例如:

// 路由配置
{
  path: '/user/:id',
  component: UserComponent
}

// 跳转
router.push('/user/123')

// 获取参数
this.$route.params.id // 123

History模式下的服务端配置

当你使用history模式时,服务器应该正确的配置,以便在刷新页面时能够重定向到正确的路径。举一个栗子,假设我们的服务器是Nginx,需要在配置文件中添加以下配置:

location / {
  try_files $uri $uri/ /index.html;
}

这将使全部的路由请求都返回index.html页面,应用程序就可以在客户端接管。

示例

Hash模式下的示例

在hash模式下,我们可以定义如下路由:

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

上述路由配置中,我们定义了两个路由://about

在页面中可以通过<router-link>标签来切换路由。

<div>
  <h1>Hello Vue-router Hash Mode!</h1>
  <router-link to="/">Home</router-link>
  <router-link to="/about">About</router-link>
  <router-view></router-view>
</div>

History模式下的示例

在history模式下,我们需要在服务器中做出如下配置:

location / {
  try_files $uri $uri/ /index.html;
}

然后定义如下路由:

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

与hash模式下相似,我们同样可以通过<router-link>标签来切换路由。

<div>
  <h1>Hello Vue-router History Mode!</h1>
  <router-link to="/">Home</router-link>
  <router-link to="/about">About</router-link>
  <router-view></router-view>
</div>

总结

通过本文的学习,我们了解了Vue-router两种路由模式的区别、以及注意事项。对于前端路由的学习和掌握,这是至关重要的,它会极大提高你的开发效率和代码的可维护性。

相关文章