vue实现底部导航栏
Vue 实现底部导航栏的方法
使用 Vue Router 和固定定位
创建底部导航栏组件,结合 Vue Router 实现路由跳转,并通过 CSS 固定定位使其始终显示在底部。
<template>
<div class="tab-bar">
<router-link
v-for="(item, index) in tabs"
:key="index"
:to="item.path"
class="tab-item"
>
<span class="icon">{{ item.icon }}</span>
<span class="text">{{ item.text }}</span>
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ path: '/home', icon: '🏠', text: '首页' },
{ path: '/category', icon: '📚', text: '分类' },
{ path: '/cart', icon: '🛒', text: '购物车' },
{ path: '/profile', icon: '👤', text: '我的' }
]
}
}
}
</script>
<style scoped>
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
background: #fff;
box-shadow: 0 -1px 10px rgba(0,0,0,0.1);
}
.tab-item {
flex: 1;
text-align: center;
padding: 8px 0;
color: #666;
text-decoration: none;
}
.tab-item.router-link-active {
color: #42b983;
}
.icon {
display: block;
font-size: 22px;
}
.text {
font-size: 12px;
}
</style>
使用第三方 UI 库
许多 Vue UI 组件库提供了现成的底部导航栏组件,可以快速集成。
安装 Vant UI 库:
npm install vant
使用 Vant 的 Tabbar 组件:
<template>
<van-tabbar v-model="active" fixed>
<van-tabbar-item icon="home-o">首页</van-tabbar-item>
<van-tabbar-item icon="search">搜索</van-tabbar-item>
<van-tabbar-item icon="cart-o">购物车</van-tabbar-item>
<van-tabbar-item icon="user-o">我的</van-tabbar-item>
</van-tabbar>
</template>
<script>
import { Tabbar, TabbarItem } from 'vant';
export default {
components: {
[Tabbar.name]: Tabbar,
[TabbarItem.name]: TabbarItem
},
data() {
return {
active: 0
}
}
}
</script>
动态切换导航栏
根据路由变化自动高亮当前导航项,在 Vue Router 中设置路由元信息。
// router.js
const routes = [
{
path: '/home',
component: Home,
meta: { tabIndex: 0 }
},
{
path: '/category',
component: Category,
meta: { tabIndex: 1 }
}
]
在导航栏组件中监听路由变化:
watch: {
'$route'(to) {
this.active = to.meta.tabIndex;
}
}
添加过渡动画
为导航栏切换添加平滑的过渡效果。
<template>
<transition name="fade">
<div class="tab-bar" v-show="show">
<!-- 导航内容 -->
</div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
响应式设计
通过媒体查询调整导航栏在不同设备上的显示效果。
@media (max-width: 768px) {
.tab-item {
padding: 6px 0;
}
.icon {
font-size: 18px;
}
}
这些方法可以根据项目需求灵活组合使用,实现功能完善且美观的底部导航栏。







