vue 底部菜单实现
实现 Vue 底部菜单的方法
使用 vant 组件库的 Tabbar
安装 vant 库后,可以直接使用 van-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="friends-o">好友</van-tabbar-item>
<van-tabbar-item icon="setting-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>
自定义底部菜单
如果不想依赖 UI 库,可以手动实现一个底部菜单。
<template>
<div class="bottom-menu">
<div
v-for="(item, index) in menuItems"
:key="index"
class="menu-item"
:class="{ 'active': activeIndex === index }"
@click="activeIndex = index"
>
<span>{{ item.label }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeIndex: 0,
menuItems: [
{ label: '首页' },
{ label: '搜索' },
{ label: '好友' },
{ label: '设置' },
],
};
},
};
</script>
<style>
.bottom-menu {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: space-around;
background: #fff;
padding: 10px 0;
box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
}
.menu-item {
padding: 5px 10px;
cursor: pointer;
}
.menu-item.active {
color: #1989fa;
font-weight: bold;
}
</style>
结合路由实现页面切换
底部菜单通常需要配合 Vue Router 进行页面切换。
<template>
<div class="bottom-menu">
<router-link
v-for="(item, index) in menuItems"
:key="index"
:to="item.path"
class="menu-item"
active-class="active"
>
<span>{{ item.label }}</span>
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
menuItems: [
{ label: '首页', path: '/' },
{ label: '搜索', path: '/search' },
{ label: '好友', path: '/friends' },
{ label: '设置', path: '/settings' },
],
};
},
};
</script>
使用 element-ui 的 el-menu
如果项目使用 element-ui,可以利用 el-menu 的 horizontal 模式实现底部菜单。
<template>
<el-menu
mode="horizontal"
class="bottom-menu"
:default-active="activeIndex"
@select="handleSelect"
>
<el-menu-item index="1">首页</el-menu-item>
<el-menu-item index="2">搜索</el-menu-item>
<el-menu-item index="3">好友</el-menu-item>
<el-menu-item index="4">设置</el-menu-item>
</el-menu>
</template>
<script>
export default {
data() {
return {
activeIndex: '1',
};
},
methods: {
handleSelect(index) {
console.log('选中菜单:', index);
},
},
};
</script>
<style>
.bottom-menu {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: space-around;
}
</style>
注意事项
- 固定定位:使用
position: fixed确保菜单始终固定在底部。 - 路由匹配:如果结合 Vue Router,确保
active-class或active样式正确匹配当前路由。 - 兼容性:在移动端需考虑
safe-area-inset-bottom以避免被设备底部遮挡。
以上方法可根据项目需求选择适合的实现方式。







