vue-router 是 Vue.js 官方的路由库,它能够帮助你在单页面应用(SPA)中实现不同视图间的切换。vue-router 支持路由声明式配置、动态路由、嵌套路由等多种功能。Vue 4.x 引入了 vue-router v4,它与 Vue 3.x 完全兼容,支持 Composition API 并对路由配置做了一些优化。
版本特性
- Vue 3 适配:完全重构为 TypeScript,支持 Composition API。
- API 变更 :如
useRouter()替代this.$router,导航守卫更名(如beforeRouteUpdate)。
路由配置
路由的配置是一个数组,包含多个对象,每个对象包含以下常见属性:
path: 路由的路径。component: 匹配路径后展示的组件。name: 路由的名称(可选),用于编程式导航。redirect: 路由重定向。children: 嵌套路由。
基本路由配置:
js
const routes = [
{
path: '/',
component: Home,
},
{
path: '/about',
component: About,
},
];
嵌套路由:
嵌套路由用于在父路由组件内显示子路由内容:
js
const routes = [
{
path: '/',
component: Home,
children: [
{
path: 'details',
component: () => import('./components/Details.vue'),
},
],
},
];
懒加载
路由懒加载可以帮助你按需加载组件,提高应用的性能。vue-router 支持异步组件。
通过 import() 动态加载路由组件,提升性能。
示例:
js
const routes = [
{
path: '/home',
component: () => import('./components/Home.vue'), // 使用 import() 动态加载组件
}
];
路由模式
Vue Router 提供了两种常见的路由模式:
createWebHistory:使用 HTML5 的 History API 实现无刷新跳转,路径无#符号,需要服务器支持。(History模式)createWebHashHistory:使用 URL 的#部分来模拟不同的 URL,不需要服务器支持。(Hash模式)