vue tab实现例子
Vue Tab 实现示例
以下是一个基于 Vue.js 的 Tab 组件实现示例,包含动态切换和基础样式。

基础模板结构
<template>
<div class="tabs">
<div class="tabs-header">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = index"
:class="{ 'active': activeTab === index }"
>
{{ tab.title }}
</button>
</div>
<div class="tabs-content">
<div v-for="(tab, index) in tabs" :key="index" v-show="activeTab === index">
{{ tab.content }}
</div>
</div>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
activeTab: 0,
tabs: [
{ title: 'Tab 1', content: 'Content for Tab 1' },
{ title: 'Tab 2', content: 'Content for Tab 2' },
{ title: 'Tab 3', content: 'Content for Tab 3' }
]
}
}
}
</script>
样式部分
<style scoped>
.tabs {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
}
.tabs-header {
display: flex;
border-bottom: 1px solid #ddd;
}
.tabs-header button {
padding: 10px 20px;
background: none;
border: none;
cursor: pointer;
font-size: 16px;
}
.tabs-header button.active {
border-bottom: 2px solid #42b983;
color: #42b983;
}
.tabs-content {
padding: 20px;
min-height: 150px;
}
</style>
动态加载内容版本
如果需要动态加载不同组件作为 Tab 内容:
<template>
<div class="tabs">
<div class="tabs-header">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="setActiveTab(index)"
:class="{ 'active': activeTab === index }"
>
{{ tab.title }}
</button>
</div>
<div class="tabs-content">
<component :is="tabs[activeTab].component" />
</div>
</div>
</template>
<script>
import Component1 from './Component1.vue'
import Component2 from './Component2.vue'
export default {
components: {
Component1,
Component2
},
data() {
return {
activeTab: 0,
tabs: [
{ title: 'Component 1', component: 'Component1' },
{ title: 'Component 2', component: 'Component2' }
]
}
},
methods: {
setActiveTab(index) {
this.activeTab = index
}
}
}
</script>
使用 Vue Router 实现路由 Tab
对于需要与路由关联的 Tab:
const routes = [
{ path: '/tab1', component: Tab1 },
{ path: '/tab2', component: Tab2 }
]
const router = new VueRouter({
routes
})
new Vue({
router,
template: `
<div>
<router-link to="/tab1" active-class="active">Tab 1</router-link>
<router-link to="/tab2" active-class="active">Tab 2</router-link>
<router-view></router-view>
</div>
`
}).$mount('#app')







