vue实现新闻导航栏
Vue实现新闻导航栏
使用Vue实现新闻导航栏可以通过组件化开发方式,结合路由和动态数据绑定完成。以下是具体实现方法:
基础结构搭建
创建Vue组件NewsNav.vue,包含导航栏HTML结构和基本样式:
<template>
<div class="news-nav">
<ul>
<li v-for="(item, index) in navItems" :key="index">
<router-link :to="item.path">{{ item.title }}</router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
navItems: [
{ title: '首页', path: '/' },
{ title: '国内', path: '/domestic' },
{ title: '国际', path: '/international' },
{ title: '科技', path: '/technology' },
{ title: '娱乐', path: '/entertainment' }
]
}
}
}
</script>
<style scoped>
.news-nav {
background: #333;
color: white;
}
.news-nav ul {
display: flex;
list-style: none;
padding: 0;
margin: 0;
}
.news-nav li {
padding: 15px 20px;
}
.news-nav a {
color: white;
text-decoration: none;
}
.news-nav a:hover {
color: #42b983;
}
</style>
动态高亮当前路由
添加路由激活状态样式,修改router-link为:
<router-link
:to="item.path"
active-class="active"
exact-active-class="exact-active"
>
{{ item.title }}
</router-link>
在样式中添加:
.news-nav .active {
color: #42b983;
border-bottom: 2px solid #42b983;
}
响应式设计

添加媒体查询实现移动端适配:
@media (max-width: 768px) {
.news-nav ul {
flex-direction: column;
}
.news-nav li {
padding: 10px;
text-align: center;
}
}
数据动态加载
从API获取导航数据:
export default {
data() {
return {
navItems: []
}
},
async created() {
try {
const response = await fetch('/api/nav-items');
this.navItems = await response.json();
} catch (error) {
console.error('加载导航数据失败:', error);
}
}
}
添加交互效果

实现下拉菜单功能:
<template>
<div class="news-nav">
<ul>
<li v-for="(item, index) in navItems" :key="index" @mouseenter="showSubNav(index)" @mouseleave="hideSubNav(index)">
<router-link :to="item.path">{{ item.title }}</router-link>
<ul v-if="item.subItems && isSubNavVisible[index]" class="sub-nav">
<li v-for="(subItem, subIndex) in item.subItems" :key="subIndex">
<router-link :to="subItem.path">{{ subItem.title }}</router-link>
</li>
</ul>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
isSubNavVisible: []
}
},
methods: {
showSubNav(index) {
this.$set(this.isSubNavVisible, index, true);
},
hideSubNav(index) {
this.$set(this.isSubNavVisible, index, false);
}
}
}
</script>
<style>
.sub-nav {
position: absolute;
background: #444;
padding: 0;
margin-top: 15px;
}
.sub-nav li {
padding: 10px 20px;
white-space: nowrap;
}
</style>
与Vuex集成
使用Vuex管理导航状态:
// store/modules/nav.js
export default {
state: {
navItems: []
},
mutations: {
SET_NAV_ITEMS(state, items) {
state.navItems = items;
}
},
actions: {
async fetchNavItems({ commit }) {
const response = await fetch('/api/nav-items');
commit('SET_NAV_ITEMS', await response.json());
}
}
}
在组件中使用:
import { mapState } from 'vuex';
export default {
computed: {
...mapState('nav', ['navItems'])
},
created() {
this.$store.dispatch('nav/fetchNavItems');
}
}






