ButtonGroup.vue 2.92 KB
<template>
  <view class="button-group">
    <template v-for="(item, index) in selectList">
      <view
        :key="index"
        class="button-item"
        :class="{ active: index === selectIndex }"
        @click="chooseType(index, item)"
        :style="{ width: itemWidth + 'rpx' }"
      >
        <text class="label">{{ item[labelKey] }}</text>
        <template v-if="item.dot && item.dot()">
          <view class="dot"></view>
        </template>
        <!-- 选中时的背景动画元素 -->
        <view class="active-bg" v-if="index === selectIndex"></view>
      </view>
      <view class="divider" v-if="index < selectList.length - 1" :key="'divider-' + index"></view>
    </template>
  </view>
</template>

<script type='text/ecmascript-6'>
export default {
  props: {
    selectList: {
      type: Array,
      default: () => []
    },
    labelKey: {
      type: String,
      default: 'label'
    }
  },
  data() {
    return {
      selectIndex: 0,
      itemWidth: 140, // 按钮固定宽度
    }
  },
  methods: {
    chooseType(index, item) {
      if (this.selectIndex === index) return
      this.selectIndex = index
      this.$emit('chooseType', { item, index })
    }
  }
}
</script>

<style scoped lang='scss'>
.button-group {
  display: flex;
  align-items: center;
  /* 移除容器背景,因为现在由外部 filter-container 提供 */
  background: transparent;
  height: toRpx(64); /* 略微减小高度 */

  .button-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    /* width由行内样式控制 */
    /* margin-right由行内样式控制 */
    padding: 0; 
    font-size: toRpx(26);
    color: #555;
    border-radius: toRpx(32); /* 胶囊形状 */
    transition: all 0.2s ease;
    cursor: pointer;
    background: #ffffff; /* 默认白底 */
    border: 1px solid #ebedf0; /* 默认浅色边框 */
    position: relative;
    box-sizing: border-box;
    overflow: hidden; /* 确保动画不溢出 */

    .label {
      position: relative;
      z-index: 2; /* 文字在最上层 */
    }

    .dot {
      position: absolute;
      top: toRpx(8);
      right: toRpx(16);
      width: toRpx(12);
      height: toRpx(12);
      border-radius: 100%;
      background: #f24724;
      z-index: 3;
    }

    /* 激活状态的背景层 */
    .active-bg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: #eef4ff;
      z-index: 1;
      animation: pulse-fade 0.3s cubic-bezier(0.25, 0.8, 0.5, 1) forwards;
    }

    &.active {
      color: #3773f8;
      font-weight: 500;
      border-color: #3773f8;
      box-shadow: 0 toRpx(2) toRpx(8) rgba(55, 115, 248, 0.15);
    }
  }

  .divider {
    width: 1px;
    height: toRpx(32);
    background: #ebedf0;
    margin: 0 toRpx(12);
  }
}

@keyframes pulse-fade {
  0% {
    opacity: 0;
    transform: scale(0.8);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}
</style>