vue路由实现导航栏
实现导航栏的基本路由配置
在Vue项目中,使用vue-router实现导航栏功能需要先安装并配置路由。通过Vue CLI创建项目时可以选择包含vue-router,或者后续手动安装:
npm install vue-router
在src/router/index.js中配置基本路由:
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
创建导航栏组件
新建src/components/NavBar.vue组件,使用<router-link>实现导航跳转:
<template>
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
</template>
<style scoped>
nav {
display: flex;
gap: 1rem;
padding: 1rem;
background: #f0f0f0;
}
.router-link-active {
font-weight: bold;
color: #42b983;
}
</style>
在主应用中挂载路由和导航栏
在src/App.vue中引入并使用导航栏组件:
<template>
<NavBar />
<router-view />
</template>
<script>
import NavBar from './components/NavBar.vue'
export default {
components: { NavBar }
}
</script>
动态高亮当前路由链接
可以通过active-class属性自定义激活状态的类名,或使用exact-active-class精确匹配:
<router-link
to="/about"
active-class="active-link"
exact-active-class="exact-active-link">
About
</router-link>
编程式导航实现
除了<router-link>,也可以通过JavaScript实现导航跳转:
methods: {
goToAbout() {
this.$router.push('/about')
// 或使用命名路由
// this.$router.push({ name: 'About' })
}
}
嵌套路由实现多级导航
对于复杂布局,可以配置嵌套路由:
const routes = [
{
path: '/user',
component: UserLayout,
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'settings',
component: UserSettings
}
]
}
]
导航守卫控制访问权限
使用路由守卫实现权限控制:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login')
} else {
next()
}
})
响应式路由参数
在组件中访问动态路由参数:
export default {
computed: {
userId() {
return this.$route.params.id
}
},
watch: {
$route(to, from) {
// 对路由变化作出响应
}
}
}






