用vue2写一个选项卡
时间: 2024-03-13 14:22:44 浏览: 50
好的,以下是一个基本的选项卡组件的 Vue 2 代码示例:
```html
<template>
<div class="tabs">
<div class="tabs-header">
<div v-for="(tab, index) in tabs" :key="index" :class="{ active: activeTab === index }" @click="activeTab = index">
{{ tab.title }}
</div>
</div>
<div class="tabs-content">
<slot :name="tabs[activeTab].name"></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 0,
tabs: []
}
},
created() {
// 添加选项卡内容
this.tabs.push({
title: 'Tab 1',
name: 'tab1'
});
this.tabs.push({
title: 'Tab 2',
name: 'tab2'
});
this.tabs.push({
title: 'Tab 3',
name: 'tab3'
});
}
}
</script>
<style>
.tabs {
display: flex;
flex-direction: column;
border: 1px solid #ccc;
}
.tabs-header {
display: flex;
justify-content: space-between;
background-color: #f0f0f0;
padding: 10px;
}
.tabs-header div {
cursor: pointer;
margin-right: 10px;
padding: 10px;
border: 1px solid #ccc;
border-bottom: none;
}
.tabs-header div:last-child {
margin-right: 0;
}
.tabs-header div.active {
background-color: #fff;
border-bottom: none;
}
.tabs-content {
padding: 10px;
border: 1px solid #ccc;
}
</style>
```
使用时,只需在 `tabs` 数组中添加选项卡的内容即可。例如:
```html
<template>
<div>
<Tabs>
<div slot="tab1">Tab 1 Content</div>
<div slot="tab2">Tab 2 Content</div>
<div slot="tab3">Tab 3 Content</div>
</Tabs>
</div>
</template>
<script>
import Tabs from './Tabs.vue';
export default {
components: {
Tabs
}
}
</script>
```
阅读全文