SegmentedControl.vue 2.87 KB
<script setup>
/**
 * 分段控件。2–4 个互斥选项用它,不用下拉 —— 选项少的时候点开才能看全是多一步。
 *
 * @typedef {{ value: string|number, label: string }} Segment
 * @typedef {'sm'|'md'|'lg'} SegmentedSize
 */

defineProps({
  modelValue: { type: [String, Number], required: true },
  /** @type {import('vue').PropType<Segment[]>} */
  options: { type: Array, required: true },
  disabled: { type: Boolean, default: false },
  /** @type {import('vue').PropType<SegmentedSize>} 与同尺寸的 Input / Select / Button 等高。 */
  size: { type: String, default: 'md' },
})

defineEmits(['update:modelValue'])
</script>

<template>
  <div
    class="drama-segmented"
    :class="`drama-segmented--${size}`"
    role="radiogroup"
  >
    <button
      v-for="option in options"
      :key="option.value"
      type="button"
      role="radio"
      class="drama-segmented__item"
      :class="{ 'is-active': option.value === modelValue }"
      :aria-checked="option.value === modelValue"
      :disabled="disabled"
      @click="$emit('update:modelValue', option.value)"
    >
      {{ option.label }}
    </button>
  </div>
</template>

<style scoped>
.drama-segmented {
  box-sizing: border-box;
  display: inline-flex;
  align-items: stretch;
  gap: 2px;
  padding: 2px;
  /* 底色与描边跟 Input / Select 同一套:白底 + 发丝边。选中段用 surface-alt 填充做「按下」感 ——
     底槽和选中段必须一深一浅,两个都填 surface-alt 就分不出选了哪个。 */
  background-color: var(--drama-color-surface);
  border: 1px solid var(--drama-color-border);
  border-radius: var(--drama-radius-sm);
}

/* 高度取 control token,和同尺寸的 Input / Select / Button 等高。 */
.drama-segmented--sm {
  height: var(--drama-control-height-sm);
}

.drama-segmented--md {
  height: var(--drama-control-height-md);
}

.drama-segmented--lg {
  height: var(--drama-control-height-lg);
}

.drama-segmented__item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 var(--drama-space-md);
  border: 0;
  border-radius: calc(var(--drama-radius-sm) - 2px);
  background: transparent;
  color: var(--drama-color-text-muted);
  font-family: var(--drama-font-family-body);
  font-size: var(--drama-font-size-sm);
  line-height: var(--drama-line-height-tight);
  white-space: nowrap;
  cursor: pointer;
  transition: background-color 0.15s ease, color 0.15s ease;
}

.drama-segmented__item:hover:not(:disabled):not(.is-active) {
  color: var(--drama-color-text);
}

.drama-segmented__item.is-active {
  background-color: var(--drama-color-surface-alt);
  color: var(--drama-color-text);
  font-weight: var(--drama-font-weight-medium);
}

.drama-segmented__item:focus-visible {
  outline: 2px solid var(--drama-color-primary);
  outline-offset: -2px;
}

.drama-segmented__item:disabled {
  opacity: 0.55;
  cursor: not-allowed;
}
</style>