实现功能:
切换,相当于tab
1、非组件代码:
<template><div><div class="tabStyle"><div v-for="(item,index) in tabTitle" :key="index" class="bordItemStyle" :class="choseIndex===index?'itemActiveStyle':'itemStyle'" @click="handleChose(index)">{{item}}</div></div></div>
</template><script>export default {name: "home",data() {return {choseIndex: 0,tabTitle:['近7天','近15天','近30天'],}},mounted() {},methods: {handleChose(index) {this.choseIndex = index;},}}
</script><style lang="scss" scoped>.tabStyle {display: flex;.itemStyle {background-color: #ffffff;}.itemActiveStyle {color: #ffffff;background-color: #025DF4;}.itemStyle,.itemActiveStyle {padding: 8px 20px;cursor: pointer;}.bordItemStyle {border-top: 1px solid rgb(220, 223, 230);border-bottom: 1px solid rgb(220, 223, 230);border-left: 1px solid rgb(220, 223, 230);&:last-child {border-right: 1px solid rgb(220, 223, 230);}}}
</style>
2、转换为组件代码
组件:文件src/components/TabBlock/index.vue
有两个要传递的参数,选项名tabTitle,激活的选项索引activeIndex.还有一个要传递的事件handleChange,该事件有一个参数index。
<template><div><div class="tabStyle"><div v-for="(item,index) in tabTitle" :key="index" class="bordItemStyle" :class="activeIndex===index?'itemActiveStyle':'itemStyle'" @click="$emit('handleChange',index)">{{item}}</div></div></div>
</template><script>export default {name: "TabBlock",props: {tabTitle: {type: Array,default: ''},activeIndex: {type: Number,default: ''},},data() {return {}},mounted() {},methods: {}}
</script><style lang="scss" scoped>.tabStyle {display: flex;.itemStyle {background-color: #ffffff;}.itemActiveStyle {color: #ffffff;background-color: #025DF4;}.itemStyle,.itemActiveStyle {padding: 8px 20px;cursor: pointer;}.bordItemStyle {border-top: 1px solid rgb(220, 223, 230);border-bottom: 1px solid rgb(220, 223, 230);border-left: 1px solid rgb(220, 223, 230);&:last-child {border-right: 1px solid rgb(220, 223, 230);}}}
</style>
调用组件的文件
<template><div><TabBlock :tabTitle="titles" :activeIndex="choseIndex" @handleChange="handleChose"></TabBlock></div>
</template><script>import TabBlock from '@/components/TabBlock/index.vue'export default {name: "home",components:{TabBlock},data() {return {titles:['近7天','近15天','近30天'],choseIndex:0,}},mounted() {},methods: {handleChose(index){this.choseIndex = index;console.log("选中的索引",this.choseIndex)console.log("选中的名称",this.titles[this.choseIndex])}}}
</script><style lang="scss" scoped></style>
效果: