vue实现底部tab
使用 Vue Router 实现底部 Tab
在 Vue 项目中,可以通过 vue-router 结合自定义组件实现底部 Tab 导航。创建一个 TabBar 组件,并在路由配置中定义每个 Tab 对应的页面。
<template>
<div class="tab-bar">
<router-link
v-for="(item, index) in tabs"
:key="index"
:to="item.path"
class="tab-item"
>
<span>{{ item.name }}</span>
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ name: '首页', path: '/home' },
{ name: '分类', path: '/category' },
{ name: '购物车', path: '/cart' },
{ name: '我的', path: '/profile' }
]
}
}
}
</script>
<style scoped>
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
height: 50px;
background: #fff;
border-top: 1px solid #eee;
}
.tab-item {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
}
.router-link-active {
color: #ff6700;
}
</style>
配置 Vue Router
在路由配置文件中,为每个 Tab 页面定义对应的路由。
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import Category from '@/views/Category.vue'
import Cart from '@/views/Cart.vue'
import Profile from '@/views/Profile.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/home', component: Home },
{ path: '/category', component: Category },
{ path: '/cart', component: Cart },
{ path: '/profile', component: Profile },
{ path: '/', redirect: '/home' }
]
const router = new VueRouter({
routes
})
export default router
动态高亮当前 Tab
通过 $route.path 判断当前路由,动态添加高亮样式。
<template>
<div class="tab-bar">
<div
v-for="(item, index) in tabs"
:key="index"
@click="changeTab(item.path)"
:class="['tab-item', { 'active': $route.path === item.path }]"
>
<span>{{ item.name }}</span>
</div>
</div>
</template>
<script>
export default {
methods: {
changeTab(path) {
this.$router.push(path)
}
}
}
</script>
<style scoped>
.active {
color: #ff6700;
}
</style>
使用第三方 UI 库
可以借助第三方库如 vant 快速实现底部 Tab。
npm install vant
import { Tabbar, TabbarItem } from 'vant'
Vue.use(Tabbar).use(TabbarItem)
<template>
<van-tabbar v-model="active">
<van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
<van-tabbar-item icon="search" to="/category">分类</van-tabbar-item>
<van-tabbar-item icon="cart-o" to="/cart">购物车</van-tabbar-item>
<van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
</van-tabbar>
</template>
<script>
export default {
data() {
return {
active: 0
}
}
}
</script>
注意事项
- 使用
position: fixed固定底部 Tab 位置,确保内容区域不会被遮挡。 - 路由配置中设置默认重定向,确保首次加载显示正确的 Tab 页面。
- 移动端项目需考虑适配问题,可使用
rem或vw/vh单位。







