返回

Vue Router 中的 History 模式:摆脱井号

前端

Vue Router 是 Vue.js 官方推荐的前端路由器,它允许我们轻松地管理单页面应用程序 (SPA) 中的路由。Vue Router 有两种模式:hash 模式和 history 模式。默认情况下,Vue Router 使用 hash 模式,这会在 URL 中添加一个井号 (#) 来表示不同的路由。然而,history 模式不会在 URL 中添加井号,这使得 URL 看起来更加简洁美观,也有利于 SEO。

配置步骤

配置 Vue Router 的 history 模式非常简单,只需在创建路由器实例时设置 mode 选项为 'history' 即可。例如:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

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

export default router

原理

Vue Router 的 history 模式通过利用 HTML5 History API 来实现。History API 提供了一些方法,允许我们操作浏览器的历史记录和 URL。当使用 history 模式时,Vue Router 会在每次路由切换时更新浏览器的历史记录。这意味着,当用户点击后退或前进按钮时,浏览器会加载历史记录中的相应页面,而不是重新加载整个应用程序。

注意事项

在使用 history 模式时,需要注意以下几点:

  • 需要在服务器端配置,以支持 history 模式。这通常涉及到在服务器的根目录下创建一个名为 ".htaccess" 的文件,并在其中添加以下内容:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
  • 需要在服务器端提供一个默认的 index.html 文件,以便在用户直接访问服务器的根目录时,能够加载应用程序。

结论

Vue Router 的 history 模式可以为我们的应用程序带来更加美观和 SEO 友好的 URL。通过遵循本文的步骤,你将能够轻松配置和理解 Vue Router 的 history 模式。