1.实现父传子
App.vue
<template>
<div class="app">
<tab-control :titles='["衣服","鞋子","裤子"]'></tab-control>
<tab-control :titles='["流行","最新","优选","数码"]'></tab-control>
</div>
</template>
<script>
import TabControl from "./TabControl"
export default {
components:{
TabControl
}
}
</script>
<style scoped>
</style>
TabControl.vue
<template>
<div class="tab-control">
<template v-for="item in titles" :key="item">
<div class="tab-control-item">{{item}}</div>
</template>
</div>
</template>
<script>
import TabControl from "./TabControl"
export default {
props:{
titles:{
type:Array,
default:()=>[]
}
}
}
</script>
<style scoped>
.tab-control
{
display: flex;
height: 44px;
line-height: 44px;
text-align: center;
}
.tab-control-item
{
flex: 1;
}
</style>
易错:
:titles='["衣服","鞋子","裤子"]'这里是"[]",不是[]
2.实现点击下方出现颜色条
如何实现点击获取当前index
注意v-for也要写上index,@click写上参数index
<template v-for="(item,index) in titles" :key="item">
<div class="tab-control-item"
@click="tabItemClick(index)"
:class="{active:index==currentIndex}">{{item}}</div>
</template>
export default {
props:{
titles:{
type:Array,
default:()=>[]
}
},
data()
{
return{
currentIndex:0
}
},
emits:["tabItemClick"],
methods:{
tabItemClick(index)
{
this.currentIndex=index
this.$emit("tabItemClick",index)
}
}
}
此处.active无空格
.tab-control-item.active
为了确保父组件知道发送了这个函数,emit要写入此函数
emits:["tabItemClick"],
methods:{
tabItemClick(index)
{
this.currentIndex=index
this.$emit("tabItemClick",index)
}
}
接着父元素@此函数,
<tab-control
:titles='["衣服","鞋子","裤子"]'
@tab-item-click="tabItemClick">
</tab-control>
methods:
{
tabItemClick(index)
{
console.log("app",index)
}
}
全部代码
App.vue
<template>
<div class="app">
<!-- tab -->
<tab-control
:titles='["衣服","鞋子","裤子"]'
@tab-item-click="tabItemClick">
</tab-control>
<!-- 展示内容 -->
<h1 >{{pageContents[currentIndex]}}</h1>
</div>
</template>
<script>
import TabControl from "./TabControl"
export default {
data()
{
return{
pageContents:["衣服列表","鞋子列表","裤子列表"],
currentIndex:0
}
},
components:{
TabControl
},
methods:
{
tabItemClick(index)
{
console.log("app",index)
this.currentIndex=index
}
}
}
</script>
<style scoped>
</style>
TabControl.vue
<template>
<div class="tab-control">
<template v-for="(item,index) in titles" :key="item">
<div class="tab-control-item"
@click="tabItemClick(index)"
:class="{active:index==currentIndex}">
<span>{{item}}</span>
</div>
</template>
</div>
</template>
<script>
import TabControl from "./TabControl"
export default {
props:{
titles:{
type:Array,
default:()=>[]
}
},
data()
{
return{
currentIndex:0
}
},
emits:["tabItemClick"],
methods:{
tabItemClick(index)
{
this.currentIndex=index
this.$emit("tabItemClick",index)
}
}
}
</script>
<style scoped>
.tab-control
{
display: flex;
height: 44px;
line-height: 44px;
text-align: center;
}
.tab-control-item
{
flex: 1;
}
.tab-control-item.active
{
color:red;
font-weight: 700;
}
.tab-control-item.active span
{
border-bottom: 3px solid red;
}
</style>