vue实现横向导航
实现横向导航的基本结构
在Vue中实现横向导航,可以使用<ul>和<li>标签结合CSS样式。导航数据通常通过Vue的data或props传递,动态渲染导航项。
<template>
<nav class="horizontal-nav">
<ul>
<li v-for="item in navItems" :key="item.id">
<a :href="item.link">{{ item.text }}</a>
</li>
</ul>
</nav>
</template>
<script>
export default {
data() {
return {
navItems: [
{ id: 1, text: "首页", link: "/" },
{ id: 2, text: "产品", link: "/products" },
{ id: 3, text: "关于", link: "/about" },
],
};
},
};
</script>
添加CSS样式
横向导航的核心是通过CSS将<li>默认的垂直排列改为水平排列,并调整间距和样式。

<style scoped>
.horizontal-nav ul {
list-style: none;
padding: 0;
margin: 0;
display: flex; /* 关键属性:启用Flex布局 */
gap: 20px; /* 导航项间距 */
}
.horizontal-nav li a {
text-decoration: none;
color: #333;
padding: 8px 12px;
border-radius: 4px;
}
.horizontal-nav li a:hover {
background-color: #f0f0f0;
}
</style>
响应式适配
通过媒体查询调整导航布局,在小屏幕下改为折叠菜单(如汉堡菜单)。

@media (max-width: 768px) {
.horizontal-nav ul {
flex-direction: column; /* 改为垂直排列 */
}
}
使用Vue Router实现路由导航
若项目集成Vue Router,可将<a>替换为<router-link>,实现单页应用的无刷新跳转。
<template>
<nav class="horizontal-nav">
<ul>
<li v-for="item in navItems" :key="item.id">
<router-link :to="item.link">{{ item.text }}</router-link>
</li>
</ul>
</nav>
</template>
添加交互效果
通过Vue的动态类绑定实现选中状态高亮。
<router-link
:to="item.link"
active-class="active-link"
>
{{ item.text }}
</router-link>
.active-link {
font-weight: bold;
color: #42b983; /* Vue主题色 */
}






