vue实现横向导航
Vue 实现横向导航的方法
使用 Flex 布局实现横向导航
在 Vue 中,可以通过 CSS Flex 布局快速实现横向导航。创建一个导航组件,并使用 Flex 布局使其水平排列。

<template>
<div class="nav-container">
<ul class="nav-list">
<li v-for="(item, index) in navItems" :key="index" class="nav-item">
<a :href="item.link">{{ item.text }}</a>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
navItems: [
{ text: '首页', link: '/' },
{ text: '产品', link: '/products' },
{ text: '关于我们', link: '/about' },
{ text: '联系我们', link: '/contact' }
]
}
}
}
</script>
<style>
.nav-container {
width: 100%;
background-color: #f8f8f8;
padding: 10px 0;
}
.nav-list {
display: flex;
list-style: none;
padding: 0;
margin: 0;
justify-content: center;
}
.nav-item {
margin: 0 15px;
}
.nav-item a {
text-decoration: none;
color: #333;
font-weight: bold;
}
.nav-item a:hover {
color: #42b983;
}
</style>
使用 Vue Router 实现横向导航
如果项目使用 Vue Router,可以结合路由实现导航功能,并添加动态激活样式。

<template>
<nav class="router-nav">
<router-link
v-for="(item, index) in routes"
:key="index"
:to="item.path"
class="nav-link"
active-class="active"
>
{{ item.name }}
</router-link>
</nav>
</template>
<script>
export default {
data() {
return {
routes: [
{ path: '/', name: '首页' },
{ path: '/products', name: '产品' },
{ path: '/about', name: '关于我们' },
{ path: '/contact', name: '联系我们' }
]
}
}
}
</script>
<style>
.router-nav {
display: flex;
background-color: #f0f0f0;
padding: 10px;
}
.nav-link {
padding: 8px 16px;
margin: 0 5px;
text-decoration: none;
color: #333;
border-radius: 4px;
}
.nav-link:hover {
background-color: #e0e0e0;
}
.active {
background-color: #42b983;
color: white;
}
</style>
响应式横向导航
对于移动端适配,可以添加媒体查询使导航在不同屏幕尺寸下表现良好。
@media (max-width: 768px) {
.nav-list {
flex-direction: column;
align-items: center;
}
.nav-item {
margin: 5px 0;
}
}
使用 UI 框架快速实现
如果项目中使用 Element UI 或 Vuetify 等框架,可以直接使用其提供的导航组件。
<template>
<el-menu mode="horizontal" :default-active="activeIndex" @select="handleSelect">
<el-menu-item index="1">首页</el-menu-item>
<el-submenu index="2">
<template slot="title">产品</template>
<el-menu-item index="2-1">产品1</el-menu-item>
<el-menu-item index="2-2">产品2</el-menu-item>
</el-submenu>
<el-menu-item index="3">关于我们</el-menu-item>
</el-menu>
</template>
<script>
export default {
data() {
return {
activeIndex: '1'
}
},
methods: {
handleSelect(key) {
console.log(key)
}
}
}
</script>
以上方法提供了从基础到进阶的横向导航实现方案,可根据项目需求选择适合的方式。






