<template> <!-- tab选项卡滑动切换 --> <view class="my-tab" ref="myTabRef"> <view class="my-tab-item" v-for="(item, index) in tabs" :ref="`tab${item.name}Ref`" :class="{ active: item.name === activeItem }" :key="index"> <view class="my-tab-text" ref="tabName" @click="tabClick(item,index)"> <view class="name">{{ item.label }}</view> <view class="xian" v-if='isshow'></view> </view> </view> </view> </template> <script> /* tabs -- 传入标签名 array类型 : tabs: [{name: "tabOne",label: "全部"},{...}] activeItem -- 默认第一个class名 string @tabClick -- 自定义点击事件 回传用到 做逻辑判断 标签大小、默认颜色、选中颜色,下边框线等样式,已在css中注释,请根据注释修改即可 */ export default { name: "cx-navTitle", props: { tabs: { //所有标签名 type: Array, default: [] }, activeItem: { //默认第一个 选中的class类名 type: String, default: '' }, show: { type: Boolean, default: '' }, }, data() { return { isshow: true, }; }, mounted() { this.isshow = this.show }, methods: { // tab点击 tabClick(item, index) { this.$emit('tabClick', item) //回传数据 // 触发滑动方法 this.scrollLeftTo(item.name); }, // 滑动 scrollLeftTo(name) { const ref = `tab${name}Ref`; // 获取myTabRef的DOM元素,即类名为my-tab的标签 const nav = this.$refs.myTabRef.$el; // 获取当前点击的某一个tab的的DOM元素,即类名为my-tab-item的标签 const title = this.$refs[ref][0].$el; // 计算位移偏差 // #ifdef H5 const to = title.offsetLeft - (nav.offsetWidth - title.offsetWidth) / 2; nav.scrollLeft = to; // #endif }, }, }; </script> <style lang="scss"> .my-tab { width: 720rpx; margin: 0 auto; // height:80rpx; // background: #ffffff; // line-height:80rpx; // border:1px solid red; display: flex; overflow-x: scroll; padding-right: 0rpx; scroll-behavior: smooth; //平稳的滑动效果 font-size: 32rpx; font-family: PingFang-SC-Heavy; .my-tab-item { padding: 20rpx 35rpx; //标签上下左右距离 -- 在这里改 color: #707070; //标签默认颜色 -- 在这里改 // height: 0rpx; text-align: center; flex: 1 0 auto; &.active { color: #333333; //标签选中颜色 -- 在这里改 font-family: PingFang-SC-Heavy; font-weight: 600; position: relative; .my-tab-text { .xian { position: relative; top: 0rpx; //下边框线和标签距离 -- 在这里改 z-index: 8; width: 26px; margin: 0 auto; border: 1rpx solid #F84221; //标签底部下边框线 -- 在这里改 border-radius: 50rpx; padding: 0rpx 30rpx; opacity: 0.6; //下边框线透明度 -- 在这里改 } .name { position: relative; z-index: 9; font-size: 32rpx; font-family: PingFang SC; font-weight: 500; color: #F84221; color: #F84221; } } } } } // 隐藏滚动条 ::-webkit-scrollbar { height: 0; width: 0; color: transparent; } </style>