App.vue
<template>
<div>
<tab-bar :tabTitle="tabTitle" @showContent="showContent"></tab-bar>
<!-- tab内容 -->
<h1>{{ tabContent[curIndex] }}</h1>
</div>
</template>
<script>
import TabBar from './components/TabBar.vue'
export default {
components: { TabBar },
data() {
return {
tabTitle: ['tabl1', 'tabl2', 'tabl3'],
tabContent: ['AAA', 'BBB', 'CCC'],
curIndex: 0
}
},
methods: {
showContent(index) {
this.curIndex = index
},
},
}
</script>
<style scoped></style>
TabBar.vue
<template>
<div>
<header>
<div class="tabItem" v-for="(item, index) in tabTitle" :key="item" @click="handleClick(index)"
:class="{ active: curIndex === index }">{{ item }}</div>
</header>
</div>
</template>
<script>
export default {
data() {
return {
curIndex: 0
}
},
props: ['tabTitle'],
emits: ['showContent'],
methods: {
handleClick(index) {
this.curIndex = index
// 抛出自定义事件,将参数下标index传递给父组件
this.$emit('showContent', index)
}
}
}
</script>
<style scoped lang="less">
header {
display: flex;
text-align: center;
.tabItem {
flex: 1;
border: 1px solid #000;
}
}
.active {
color: pink;
}
</style>