uniapp组件-自定义tab组件

uniapp自定义tab选项卡组件

效果(正常的和滚动的)

请添加图片描述

请添加图片描述

代码

<template>
  <view class="custom-tab-com">
    <scroll-view
      :scroll-x="scrollable"
      class="custom-tabs"
      @scroll="scroll"
      scroll-with-animation
      :scroll-left="scrollLeft"
    >
      <view class="in" :style="[customStyle, inStyle]">
        <view
          class="item"
          v-for="(item, index) in list"
          @click="tabClick(item)"
          :class="[`item-${index}`, { selected: item.value === tabValue }]"
          :style="[getItemStyle(item.value === tabValue), itemStyle]"
          :key="index"
        >
          {{ item.name }}
        </view>
        <view
          v-show="showLine"
          class="active-item"
          :style="[{ left: left + 'px' }, customLineStyle]"
        ></view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  name: 'CustomTab',
  components: {},
  props: {
    list: {
      type: Array,
      default: () => {
        // {
        //     name:'',
        //     value:''
        // }
        return []
      },
    },
    modelValue: {
      type: String,
      default: '',
    },
    scrollable: {
      type: Boolean,
      default: true,
    },
    // 线条宽度 单位rpx
    lineWidth: {
      type: String,
      default: '',
    },
    // 线条高度 单位rpx
    lineHeight: {
      type: String,
      default: '',
    },
    // 线条颜色
    lineColor: {
      type: String,
      default: '',
    },
    //  item得样式
    itemStyle: {
      type: Object,
      default: () => {
        return {}
      },
    },
    // class为in得样式
    customStyle: {
      type: Object,
      default: () => {
        return {}
      },
    },
    // 选中得样式
    activeStyle: {
      type: Object,
      default: () => {
        return {}
      },
    },
    // 未选择得样式
    inactiveStyle: {
      type: Object,
      default: () => {
        return {}
      },
    },
    // 居中方式,scrollable 和这个属性不能共用
    justifyContent: {
      type: String,
      default: () => {
        return ''
      },
    },
  },
  data() {
    return {
      domList: {},
      faDom: {},
      listDom: [],
      left: 0,
      showLine: false,
      scrollDetail: {},
      scrollLeft: 0,
      scrollWidth: 0,
    }
  },
  emits: ['update:modelValue', 'change'],
  computed: {
    tabValue: {
      get() {
        return this.modelValue || ''
      },
      set(newValue) {
        this.$emit('update:modelValue', newValue)
      },
    },
    customLineStyle() {
      let style = {}
      if (this.lineWidth) {
        style['width'] = this.lineWidth + 'rpx'
      }
      if (this.lineHeight) {
        style['height'] = this.lineHeight + 'rpx'
      }
      if (this.lineColor) {
        style['background'] = this.lineColor
      }
      return style
    },
    inStyle() {
      let style = {}
      if (this.justifyContent) {
        style['justify-content'] = this.justifyContent
      }
      return style
    },
  },
  watch: {
    list: {
      deep: true,
      immediate: true,
      handler(val) {
        if (!val) return
        this.$nextTick(() => {
          this.showLine = false
          this.init(val)
        })
      },
    },
  },
  mounted() {},
  created() {},
  methods: {
    async init(val) {
      const query = uni.createSelectorQuery().in(this)
      // 父元素
      this.faDom = await this.selectQuery(query, `.custom-tab-com`)
      const promiseAllArr = val.map((item, index) => {
        return this.selectQuery(query, `.item-${index}`)
      })
      // 子元素列表
      this.listDom = await Promise.all(promiseAllArr)
      this.listDom.forEach(item => {
        // 计算这个scroll的总宽度
        this.scrollWidth += item.width
      })
      if (this.listDom.length > 0) {
        this.moveLine(this.tabValue)
        this.moveScroll(this.tabValue)
      }
    },
    selectQuery(query, className) {
      return new Promise(resolve => {
        query
          .select(className)
          .boundingClientRect(data => {
            resolve(data)
          })
          .exec()
      })
    },
    tabClick(item) {
      this.tabValue = item.value
       this.$emit('change', item)
      this.moveLine(item.value)
      this.moveScroll(item.value)
    },
    // 移动线
    moveLine(val) {
      // 判断当前选中的是第几个
      const index = this.list.findIndex(item => {
        return item.value === val
      })
    
      this.showLine = true
        this.listDom[index].left +
        this.listDom[index].width / 2 -
        this.faDom.left
    },
    // 移动scroll
    moveScroll(val) {
      if (!this.scrollable) return
      // 判断当前选中的是第几个
      const index = this.list.findIndex(item => {
        return item.value === val
      })
      let scrollLeftWidth = this.listDom
        .slice(0, index)
        .reduce((total, curr) => total + curr.width, 0)
      const max = this.scrollWidth - this.faDom.width

      let scrollLeft =
        scrollLeftWidth - (this.faDom.width - this.listDom[index].width) / 2
      scrollLeft = Math.min(scrollLeft, max)
      this.scrollLeft = Math.max(0, scrollLeft)
    },
    getItemStyle(judge) {
      return judge ? this.activeStyle : this.inactiveStyle
    },
    scroll(e) {
      this.scrollDetail = e.detail
    },
  },
}
</script>
<style lang="scss" scoped>
.custom-tab-com {
  width: 100%;
  position: relative;
}
.custom-tabs {
  width: 100%;
  box-sizing: border-box;
  white-space: nowrap;
  .in {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    display: flex;
    height: 50rpx;
  }
  .item {
    // flex: 1;
    height: 42rpx;
    padding: 0 11px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
  }
}
.active-item {
  position: absolute;
  bottom: 0;
  left: 27px;
  width: 20px;
  transform: translateX(-50%);
  transition-duration: 300ms;
  height: 6rpx;
  // background: #3c9cff;
  background-size: cover;
}
</style>


如何使用(滚动的代码只是把数组里面多添加了几个)

const tabs = [
  {
    name: '标签一',
    value: 'one',
  },
  {
    name: '标签二',
    value: 'two',
  },
  {
    name: '标签三',
    value: 'three',
  },
]
<custom-tab
            v-model="_this.courseType"
            @change="tabsClick"
            :list="tabs"
            :scrollable="false"
            line-width="54"
            line-height="8"
            :item-style="{
              height: '46rpx',
            }"
            :custom-style="{
              height: '46rpx',
            }"
            :activeStyle="{
              color: '#3D3D3D',
              'font-family': '思源黑体500',
              'font-size': '32rpx',
            }"
            :inactiveStyle="{
              color: '#767676',
              'font-size': '32rpx',
              'font-family': '思源黑体',
            }"
            lineColor="linear-gradient(90deg, #4FB0FE 0%, rgba(255, 255, 255, 0) 100%);"
          ></custom-tab>
如果你想让文字和下面的线条之间的间距大一点,你可以在itemStyle 和 customStyle 设置高度, customStyle 减去 itemStyle 的高度差就是文字和线条的间距,
切记,不要在 customStyle 和 itemStyle 里面写margin,如果你想让两个tabItem之间的间距大一点,可以设置padding,或者你在源码里面修改
设置了横向滚动之后,justifyContent 这个属性就不要在设置了
线条过渡的时间我没有添加,给的300ms,如果你想修改可以自己添加props来修改
如果你的标签少不需要左右滚动的话,你需要把scrollable设置为false

有bug的话,欢迎在评论区指出

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是大刚啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值