vue路由实现有哪些
Vue 路由实现方式
Vue 路由主要通过官方库 vue-router 实现,支持多种路由模式和功能扩展。以下是常见的实现方式和技术细节:
基础路由配置
安装 vue-router 后,在项目中定义路由表:
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = createRouter({
history: createWebHistory(),
routes
});
在 main.js 中挂载路由:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
路由模式选择
-
Hash 模式
使用 URL 的 hash 部分(#)实现路由,兼容性更好:createRouter({ history: createWebHashHistory(), routes }); -
History 模式
依赖 HTML5 History API,需服务器配置支持:createRouter({ history: createWebHistory(), routes });
动态路由匹配
通过冒号 : 定义动态路径参数:
{ path: '/user/:id', component: User }
在组件中通过 $route.params.id 或 Composition API 的 useRoute() 获取参数。
嵌套路由
使用 children 属性定义嵌套结构:
{
path: '/parent',
component: Parent,
children: [
{ path: 'child', component: Child }
]
}
需在父组件中使用 <router-view> 作为子路由出口。
编程式导航
通过 router.push 或 <router-link> 实现跳转:
// 字符串路径
router.push('/about');
// 对象形式
router.push({ path: '/user/123' });
// 命名路由(需提前定义 name 属性)
router.push({ name: 'user', params: { id: 123 } });
路由守卫
全局或局部控制导航逻辑:
// 全局前置守卫
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) next('/login');
else next();
});
// 路由独享守卫
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => { ... }
}
路由懒加载
动态导入组件提升性能:
const User = () => import('./views/User.vue');
其他高级功能
-
路由元信息
通过meta字段传递自定义数据:{ path: '/admin', meta: { requiresAuth: true } } -
滚动行为
自定义页面切换后的滚动位置:const router = createRouter({ scrollBehavior(to, from, savedPosition) { return savedPosition || { top: 0 }; } }); -
路由过渡动画
结合<transition>实现切换动画:<router-view v-slot="{ Component }"> <transition name="fade"> <component :is="Component" /> </transition> </router-view>
第三方路由库
-
Vue Router Next
Vue 3 的官方路由库,兼容 Composition API。 -
Unplugin-Vue-Router
基于文件系统的自动路由生成工具。 -
Vite-Router
针对 Vite 的轻量级路由方案。
以上实现方式可根据项目需求灵活组合,建议参考官方文档获取最新特性支持。







