Vue实现Tab控件
使用vue实现Tab功能。创建一个tab.vue文件,内容如下:
<template>
<div class="tab_box">
<!--这里是tab的每一项-->
<div v-for="item in tabs" :key="'tabItem' + item.id" :class="['tab_item', {'active_tab':currentTab === item.id}]" @click="changeTab(item.id)">
{{item.label}}
</div>
</div>
</template>
<script>
export default {
data () {
return {
currentTab: '' // 用于记录tab当前所在项的id
}
},
props: ['tabs'], // 需要父组件传入
methods: {
changeTab (id) {
this.currentTab = id
this.$emit('changed', id) // 点击tab时触发changed方法,由父组件处理
}
},
mounted: function () {
this.currentTab = this.tabs[0].id // 默认下划线在第一项
}
}
</script>
<style>
.tab_box{
width:100%;
display:table;
}
.tab_item{
display:table-cell;
padding: 3px 8px 4px 8px;
/*如果想修改tab内的字体颜色和tab样式,在这里修改*/
}
.active_tab {
/*这是下划线样式,可以根据需要修改*/
border-bottom: 2px solid grey;
}
</style>
在父组件调用:
<tab @changed="change" :tabs="tabs"></tab>其中change方法和tabs需要父组件中定义,tabs的格式如下:
tabs: [
{'id': 't1', 'label': 'TAB1'},
{'id': 't2', 'label': 'TAB2'},
{'id': 't3', 'label': 'TAB3'},
{'id': 't4', 'label': 'TAB4'},
{'id': 't5', 'label': 'TAB5'}
],为确保正确渲染,id需要保证唯一性。label为tab显示的内容。change方法如下:
change (data) {
//这里写切换tab之后你需要做的事,data为切换后的tabId
this.message = 'this is ' + data + ', do whatever you want'
}最终效果如下:
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!