vue实现tabbar
Vue 实现 TabBar 的方法
使用 Vue Router 实现 TabBar
安装 Vue Router 并创建路由配置文件,定义每个 tab 对应的路由路径和组件。
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Profile from '../views/Profile.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/profile', component: Profile }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
创建 TabBar 组件,使用 router-link 实现导航功能。
<!-- components/TabBar.vue -->
<template>
<div class="tab-bar">
<router-link to="/" class="tab-item">首页</router-link>
<router-link to="/profile" class="tab-item">我的</router-link>
</div>
</template>
<style>
.tab-bar {
position: fixed;
bottom: 0;
width: 100%;
display: flex;
background: #fff;
box-shadow: 0 -1px 10px rgba(0,0,0,0.1);
}
.tab-item {
flex: 1;
text-align: center;
padding: 10px 0;
}
.router-link-active {
color: #42b983;
}
</style>
使用状态管理实现 TabBar

通过 Vuex 或 Pinia 管理当前选中的 tab 状态。
// store/index.js
import { defineStore } from 'pinia'
export const useTabStore = defineStore('tab', {
state: () => ({
activeTab: 'home'
}),
actions: {
setActiveTab(tab) {
this.activeTab = tab
}
}
})
TabBar 组件通过状态管理切换内容。
<!-- components/TabBar.vue -->
<template>
<div class="tab-bar">
<div
v-for="tab in tabs"
:key="tab.id"
@click="setActiveTab(tab.id)"
:class="['tab-item', { active: activeTab === tab.id }]"
>
{{ tab.label }}
</div>
</div>
</template>
<script setup>
import { useTabStore } from '../store'
import { storeToRefs } from 'pinia'
const tabStore = useTabStore()
const { activeTab } = storeToRefs(tabStore)
const { setActiveTab } = tabStore
const tabs = [
{ id: 'home', label: '首页' },
{ id: 'profile', label: '我的' }
]
</script>
动态组件实现 TabBar

使用 Vue 的动态组件根据当前 tab 切换显示内容。
<!-- App.vue -->
<template>
<TabBar @tab-change="currentTab = $event" />
<component :is="currentTabComponent" />
</template>
<script setup>
import { ref, computed } from 'vue'
import TabBar from './components/TabBar.vue'
import Home from './components/Home.vue'
import Profile from './components/Profile.vue'
const currentTab = ref('home')
const currentTabComponent = computed(() => {
return currentTab.value === 'home' ? Home : Profile
})
</script>
移动端优化
针对移动端添加点击反馈和图标支持。
<!-- components/TabBar.vue -->
<template>
<div class="tab-bar">
<div
v-for="tab in tabs"
:key="tab.id"
@click="handleTabClick(tab.id)"
:class="['tab-item', { active: activeTab === tab.id }]"
>
<i :class="tab.icon"></i>
<span>{{ tab.label }}</span>
</div>
</div>
</template>
<style>
.tab-item {
transition: all 0.2s;
}
.tab-item:active {
transform: scale(0.95);
}
</style>






