用vue实现导航
使用 Vue 实现导航
基础导航实现
在 Vue 中实现导航通常使用 vue-router 库。确保已安装 vue-router,可以通过以下命令安装:
npm install vue-router
在项目中创建一个路由配置文件(如 router/index.js),定义路由路径和组件:
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
});
export default router;
在主入口文件(如 main.js)中引入路由:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
导航菜单组件
在组件中使用 <router-link> 实现导航链接,例如在 App.vue 中:
<template>
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
<router-view />
</template>
动态路由与参数传递
可以通过动态路由传递参数,例如定义带参数的路由:

// router/index.js
const routes = [
{ path: '/user/:id', component: User }
];
在组件中通过 $route.params 获取参数:
<template>
<div>User ID: {{ $route.params.id }}</div>
</template>
导航守卫
使用导航守卫控制路由跳转逻辑,例如全局前置守卫:
// router/index.js
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
嵌套路由
实现嵌套路由需要在父路由中定义 children 属性:

// router/index.js
const routes = [
{
path: '/dashboard',
component: Dashboard,
children: [
{ path: 'profile', component: Profile },
{ path: 'settings', component: Settings }
]
}
];
在父组件中使用 <router-view> 显示子路由:
<!-- Dashboard.vue -->
<template>
<div>
<h1>Dashboard</h1>
<router-view />
</div>
</template>
路由懒加载
通过动态导入实现路由懒加载,优化性能:
// router/index.js
const routes = [
{ path: '/', component: () => import('../views/Home.vue') }
];
样式与激活状态
为当前激活的导航链接添加样式,使用 router-link-active 类:
.router-link-active {
font-weight: bold;
color: #42b983;
}






