vue路由实现流程
Vue 路由实现流程
安装 Vue Router
通过 npm 或 yarn 安装 Vue Router 依赖包:
npm install vue-router
或
yarn add vue-router
配置路由文件
在项目中创建路由配置文件(通常为 router/index.js),引入 Vue Router 并定义路由规则:
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
注入路由到 Vue 实例
在 main.js 中引入路由配置并注入到 Vue 实例:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
使用路由视图和导航
在根组件(如 App.vue)中添加 <router-view> 作为路由出口,并使用 <router-link> 实现导航:
<template>
<div id="app">
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view />
</div>
</template>
动态路由和参数传递
定义动态路由时,使用 : 标记参数:
{
path: '/user/:id',
name: 'User',
component: User
}
在目标组件中通过 $route.params 获取参数:
this.$route.params.id
路由守卫
通过路由守卫实现权限控制或逻辑拦截:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
嵌套路由
在路由配置中使用 children 定义嵌套路由:
{
path: '/user',
component: User,
children: [
{
path: 'profile',
component: UserProfile
}
]
}
在父组件中添加 <router-view> 作为子路由出口。
懒加载路由
通过动态导入实现路由组件的懒加载:

{
path: '/contact',
name: 'Contact',
component: () => import('../views/Contact.vue')
}






