vue实现导航页面
Vue 实现导航页面
使用 Vue Router 创建导航
安装 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
在组件中添加导航菜单
在 App.vue 或布局组件中添加导航链接:
<template>
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
<router-view/>
</template>
动态导航菜单实现
通过数据驱动的方式生成导航菜单:
<script>
export default {
data() {
return {
menuItems: [
{ path: '/', name: 'Home' },
{ path: '/about', name: 'About' },
{ path: '/contact', name: 'Contact' }
]
}
}
}
</script>
<template>
<nav>
<router-link
v-for="item in menuItems"
:key="item.path"
:to="item.path"
>
{{ item.name }}
</router-link>
</nav>
</template>
嵌套路由实现
配置嵌套路由:
const routes = [
{
path: '/user',
component: UserLayout,
children: [
{ path: '', component: UserProfile },
{ path: 'posts', component: UserPosts }
]
}
]
导航守卫
实现路由权限控制:
router.beforeEach((to, from, next) => {
const isAuthenticated = checkAuth()
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
响应式导航栏
实现移动端友好的响应式导航:
<template>
<div class="nav-container">
<button @click="toggleMenu">☰</button>
<div :class="['nav-links', { 'show': isMenuOpen }]">
<router-link
v-for="item in menuItems"
:key="item.path"
:to="item.path"
@click="isMenuOpen = false"
>
{{ item.name }}
</router-link>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isMenuOpen: false
}
},
methods: {
toggleMenu() {
this.isMenuOpen = !this.isMenuOpen
}
}
}
</script>
<style>
.nav-links {
display: none;
}
.nav-links.show {
display: block;
}
@media (min-width: 768px) {
.nav-links {
display: flex;
}
button {
display: none;
}
}
</style>
面包屑导航
实现路径导航提示:
<template>
<div class="breadcrumbs">
<span v-for="(crumb, index) in crumbs" :key="index">
<router-link :to="crumb.path">{{ crumb.name }}</router-link>
<span v-if="index < crumbs.length - 1"> / </span>
</span>
</div>
</template>
<script>
export default {
computed: {
crumbs() {
const pathArray = this.$route.path.split('/')
return pathArray.map((path, i) => {
return {
name: path || 'Home',
path: pathArray.slice(0, i + 1).join('/') || '/'
}
})
}
}
}
</script>






