vue实现tab多页
Vue 实现 Tab 多页
使用动态组件切换
通过 Vue 的 <component :is="currentTab"> 动态切换组件,结合 v-for 渲染标签页标题。
<template>
<div>
<div class="tabs">
<button
v-for="tab in tabs"
:key="tab.name"
@click="currentTab = tab.component"
:class="{ active: currentTab === tab.component }"
>
{{ tab.name }}
</button>
</div>
<component :is="currentTab" />
</div>
</template>
<script>
import Tab1 from './Tab1.vue';
import Tab2 from './Tab2.vue';
export default {
data() {
return {
currentTab: 'Tab1',
tabs: [
{ name: 'Tab 1', component: 'Tab1' },
{ name: 'Tab 2', component: 'Tab2' }
]
};
},
components: { Tab1, Tab2 }
};
</script>
<style>
.tabs button.active {
background: #ddd;
}
</style>
使用路由实现多页
结合 Vue Router 实现 URL 驱动的 Tab 切换,适合需要保存页面状态的场景。
// router.js
const routes = [
{ path: '/tab1', component: () => import('./Tab1.vue') },
{ path: '/tab2', component: () => import('./Tab2.vue') }
];
<template>
<div>
<router-link to="/tab1">Tab 1</router-link>
<router-link to="/tab2">Tab 2</router-link>
<router-view></router-view>
</div>
</template>
使用状态管理保存数据
通过 Vuex 或 Pinia 管理 Tab 数据,确保切换时状态不丢失。
// store.js (Pinia 示例)
import { defineStore } from 'pinia';
export const useTabStore = defineStore('tabs', {
state: () => ({
activeTab: 'Tab1',
tabData: {}
})
});
<template>
<button @click="store.activeTab = 'Tab1'">Tab 1</button>
<button @click="store.activeTab = 'Tab2'">Tab 2</button>
<component :is="store.activeTab" />
</template>
<script setup>
import { useTabStore } from './store';
const store = useTabStore();
</script>
响应式 Tab 容器
通过 CSS 和动态样式实现响应式 Tab 布局,适应不同屏幕尺寸。
.tabs {
display: flex;
overflow-x: auto;
}
.tab-content {
padding: 12px;
}
@media (max-width: 600px) {
.tabs button {
padding: 8px 12px;
font-size: 14px;
}
}
动画过渡效果
添加 Vue 过渡动画使 Tab 切换更平滑。
<transition name="fade" mode="out-in">
<component :is="currentTab" />
</transition>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}






