什么是Vue Router的路由模式?
Vue Router有两种路由模式:哈希模式(Hash Mode)和历史模式(History Mode)。
1. 哈希模式(Hash Mode)
哈希模式是Vue Router的默认模式。在哈希模式下,URL中的路由会以#
符号作为前缀,例如:http://example.com/#/about
。这个模式在大多数情况下都能正常工作,因为它不需要服务器端配置,可以在任何静态文件服务器上使用。
优点:
- 易于设置,无需服务器配置。
- 支持老版本浏览器。
缺点:
- URL中包含
#
,不太美观。 - 不适合SEO,搜索引擎难以索引
#
后面的内容。
2. 历史模式(History Mode)
历史模式使用HTML5 History API来管理路由。URL看起来更加干净,没有#
符号,例如:http://example.com/about
。为了使历史模式正常工作,需要在服务器端进行一些配置,确保所有URL都指向Vue应用。
优点:
- URL更加美观,不包含
#
。 - 更适合SEO,搜索引擎可以正常索引内容。
缺点:
- 需要服务器端配置。
- 不支持老版本浏览器,需要额外处理。
如何设置路由模式?
在Vue应用中的路由配置文件中,设置路由模式:
const router = new VueRouter({
mode: 'history', // 使用历史模式
routes: [
// 定义路由
]
})
使用哈希模式,只需将mode
设置为'hash'
即可。
示例代码
// 导入Vue和Vue Router
import Vue from 'vue'
import VueRouter from 'vue-router'
// 使用Vue Router插件
Vue.use(VueRouter)
// 创建路由实例
const router = new VueRouter({
mode: 'history', // 使用历史模式
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
// 创建Vue实例,并将路由添加到根实例中
new Vue({
el: '#app',
router, // 注入路由
render: h => h(App)
})
总结
哈希模式简单易用,适合大多数情况,而历史模式更适合需要更美观URL和SEO的情况。