Vue Router 是 Vue.js 官方的路由管理器,可以轻松地实现单页应用(SPA)的路由功能。Vue Router 提供了两种路由模式:hash
模式和 history
模式。
Hash 模式
Hash 模式是指在 URL 中使用 #
符号来表示当前页面的状态。在 Hash 模式下,当 URL 中的 #
符号后面的部分发生变化时,浏览器并不会向服务器发送请求,而是通过 JavaScript 的 hashchange
事件来监听 URL 的变化并更新页面的内容。
Hash 模式的 URL 格式如下:
http://www.example.com/#/path/to/page
其中,#/path/to/page
表示当前页面的状态。
要使用 Hash 模式,我们可以在创建 Vue Router 实例时设置 mode
选项为 'hash'
:
const router = new VueRouter({
mode: 'hash',
routes: [
// ...
]
})
History 模式
History 模式是指在 URL 中不使用 #
符号,而是使用浏览器的 history
API 来管理页面的状态。在 History 模式下,当 URL 发生变化时,浏览器会向服务器发送请求,服务器需要返回对应的 HTML 页面。然后,浏览器会将服务器返回的 HTML 页面插入到当前页面的 <body>
中,从而更新页面的内容。
History 模式的 URL 格式如下:
http://www.example.com/path/to/page
其中,/path/to/page
表示当前页面的状态。
要使用 History 模式,我们可以在创建 Vue Router 实例时设置 mode
选项为 'history'
:
const router = new VueRouter({
mode: 'history',
routes: [
// ...
]
})
需要注意的是,在使用 History 模式时,服务器需要进行配置,以便在用户访问不存在的页面时返回正确的 HTML 页面。否则,用户将看到浏览器的 404 页面。