定义在项目的基础组类别的 tab组件中,定义一个tab切换数量的数组 和一个currentIndex 当前高亮索引 的props,当前高亮(active)的类等于currentIndex === index 当前循环的索引值,增加点击派发事件传入index 索引参数,
调用组件的页面接受派发事件点击的index 索引,底下的内容根据this.currentIndex 的值v-if 显示隐藏
tab组件
<template>
<ul class="switches">
<li class="switch-item" v-for="(item,index) in switches" :class="{'active':currentIndex === index}"
@click="switchItem(index)">
<span>{{item.name}} </span>
</li>
</ul>
</template> <script type="text/ecmascript-6">
export default {
props: {
switches: {
type: Array,
default: []
},
currentIndex: {
type: Number,
default: 0
}
},
methods: {
switchItem(index) {
this.$emit('switch', index)
}
}
}
</script>
调用
<switches :switches="switches" :currentIndex="currentIndex" @switch="switchItem"></switches>
data() {
return {
currentIndex: 0,
switches: [
{
name: '最近播放'
},
{
name: '搜索历史'
}
]
}
}, switchItem(index) {
this.currentIndex = index
},