---
title: "Tag Group"
description: "A group of tags with optional selection."
url: https://weme-ui.github.io/slim/components/tag-group.md
---
# Tag Group

可选择、可移除的标签组。基于 Reka UI `TagGroup`。可以单独用，也可以放进 `FormField`。有 `FormField` 时会合并 `id` / `name` / `disabled`。选项由 `items` 驱动；监听 `remove` 后删除控件才会生效。

## Installation

```bash
pnpm dlx @weme-ui/weme-ui add tag-group
```

## Usage

```vue
<script lang="ts" setup>
import type { TagGroupItem, TagGroupItemValue } from '../tag-group.props'
import * as v from 'valibot'
import { ref } from 'vue'
import Button from '../../button/button.vue'
import FormField from '../../form-field/form-field.vue'
import Form from '../../form/form.vue'
import TagGroup from '../tag-group.vue'

const schema = v.object({
  tags: v.pipe(v.string('请选择一个标签'), v.minLength(1, '请选择一个标签')),
})

const defaultValues = {
  tags: '',
}

const items = ref<TagGroupItem[]>([
  { label: 'Design', value: 'design' },
  { label: 'Engineering', value: 'engineering' },
  { label: 'Product', value: 'product' },
])

function onRemove(values: TagGroupItemValue[]) {
  items.value = items.value.filter((item) => !values.includes(item.value))
}

function onFormSubmit(values: { tags: string }) {
  // eslint-disable-next-line no-alert
  alert(JSON.stringify(values))
}
</script>

<template>
  <Form
    class="max-w-sm w-full"
    :default-values="defaultValues"
    :schema="schema"
    @form-submit="onFormSubmit"
  >
    <FormField v-slot="{ field }" name="tags" label="Tags" required>
      <TagGroup
        :model-value="field.state.value"
        :items="items"
        selection-mode="single"
        dismissible
        @change="field.api.handleChange"
        @remove="onRemove"
      />
    </FormField>
    <Button type="submit"> Submit </Button>
  </Form>
</template>
```

## Props

| 属性                     | 说明                                                                                                                                                                 | 类型                                                                  | 默认值             |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | ------------------ |
| `as`                     | 根节点渲染为的元素或组件（Reka UI `Primitive`）                                                                                                                      | `any`                                                                 | `'div'`            |
| `asChild`                | 是否合并到子元素（Reka UI `Primitive`）                                                                                                                              | `boolean`                                                             | `false`            |
| `modelValue`             | 受控选中值；`selectionMode` 为 `multiple` 时为数组；可用 `v-model`                                                                                                   | `TagGroupItemValue \| TagGroupItemValue[]`                            | —                  |
| `defaultValue`           | 非受控初始选中值                                                                                                                                                     | `TagGroupItemValue \| TagGroupItemValue[]`                            | —                  |
| `items`                  | 标签列表；单项常用 `label`、`value`、`icon`、`selectedIcon`、`iconClass`、`class`、`disabled`、`description`；类型为 `Omit<GroupItem<string>, 'type' \| 'onSelect'>` | `TagGroupItem[]`                                                      | —                  |
| `selectionMode`          | 选择模式；`none` 时不可选中                                                                                                                                          | `'none' \| 'single' \| 'multiple'`                                    | `'none'`           |
| `disallowEmptySelection` | 为 `true` 时禁止取消最后一个选中项                                                                                                                                   | `boolean`                                                             | —                  |
| `escapeKeyBehavior`      | 按 `Escape` 时是否清空选中                                                                                                                                           | `'clearSelection' \| 'none'`                                          | `'clearSelection'` |
| `by`                     | 比较选中值的字段名或自定义比较函数                                                                                                                                   | `string \| ((a: TagGroupItemValue, b: TagGroupItemValue) => boolean)` | —                  |
| `variant`                | 外观变体                                                                                                                                                             | `'soft' \| 'outline' \| 'inverted'`                                   | `'soft'`           |
| `size`                   | 尺寸                                                                                                                                                                 | `'sm' \| 'md' \| 'lg'`                                                | `'md'`             |
| `dismissible`            | 是否显示删除按钮（`TagGroupItemDelete`）                                                                                                                             | `boolean`                                                             | —                  |
| `deleteIcon`             | 删除图标（Iconify）；`dismissible` 为真时生效                                                                                                                        | `IconifyIconProps['icon']`                                            | `'ri:close-line'`  |
| `loop`                   | 键盘导航是否在首尾循环                                                                                                                                               | `boolean`                                                             | `true`             |
| `dir`                    | 阅读方向；未传时继承 `ConfigProvider`                                                                                                                                | `'ltr' \| 'rtl'`                                                      | —                  |
| `unstyled`               | 移除样式变体类，仅保留结构                                                                                                                                           | `boolean`                                                             | —                  |
| `id`                     | 隐藏 input 的 `id`；未传时回退到 FormField Context                                                                                                                   | `string`                                                              | —                  |
| `name`                   | 隐藏 input 的 `name`；未传时回退到 FormField Context                                                                                                                 | `string`                                                              | —                  |
| `disabled`               | 是否禁用整组；会与 FormField Context 的 `disabled` 合并                                                                                                              | `boolean`                                                             | —                  |
| `class`                  | 根节点额外 class                                                                                                                                                     | `any`                                                                 | —                  |
| `ui`                     | 覆盖 slots 样式（`root` / `item` / `itemIcon` / `itemText` / `itemDelete` / `itemDeleteIcon`）                                                                       | `Partial<TagGroupStyleSlots>`                                         | —                  |

## Events

| 事件                | 说明                                                                                  | 参数                                                           |
| ------------------- | ------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `update:modelValue` | 选中值变更时触发（含 `v-model`；透传自 Reka UI Root）                                 | `value: TagGroupItemValue \| TagGroupItemValue[] \| undefined` |
| `change`            | 选中值变更时触发（由 `@update:modelValue` 转发；参数同选中值，非原生 `Event`）        | `value: TagGroupItemValue \| TagGroupItemValue[] \| undefined` |
| `remove`            | 用户移除标签时触发；**须监听此事件**删除控件才会生效，由消费方从 `items` 中移除对应项 | `values: TagGroupItemValue[]`                                  |

## Slots

| 插槽         | 说明                                                                                                              |
| ------------ | ----------------------------------------------------------------------------------------------------------------- |
| `tag-icon`   | 自定义标签图标；作用域参数 `{ item, selected }`；未传且 `item.icon` 存在时渲染 `AnimatedToggleIcon`               |
| `tag-text`   | 自定义标签文案；作用域参数 `{ item, selected }`；未传时回退到 `item.label`                                        |
| `tag-delete` | 自定义删除控件内容；作用域参数 `{ item, selected }`；仅在 `dismissible` 且该项未禁用时渲染；未传时用 `deleteIcon` |
| `empty`      | `items` 为空或不存在时的占位内容                                                                                  |

## Accessibility

基于 Reka UI `TagGroup`（`TagGroupRoot` / `TagGroupItem` / `TagGroupItemDelete`）与 `RovingFocusGroup`。有标签时根节点 `role="grid"`，单项 `role="row"`；为空时根节点 `role="group"`。`selectionMode="multiple"` 时设置 `aria-multiselectable`。指针按下时单项设置 `aria-pressed`（用于按压缩放反馈）。根节点设置 `data-slot="tag-group"`，并通过 FormField Context 合并隐藏 input 的 `id` / `name`。

### Keyboard Interactions

| Key                        | Description                                                                            |
| -------------------------- | -------------------------------------------------------------------------------------- |
| `Tab`                      | 进入 / 离开组（组内仅一项在 Tab 序中）；`dismissible` 时再按一次移到当前标签的删除按钮 |
| `ArrowLeft` / `ArrowRight` | 在标签间移动焦点；`dir` 为 `rtl` 时左右对调                                            |
| `ArrowUp` / `ArrowDown`    | 在标签间移动焦点                                                                       |
| `Home` / `PageUp`          | 将焦点移到首个可聚焦标签                                                               |
| `End` / `PageDown`         | 将焦点移到末个可聚焦标签                                                               |
| `Enter` / `Space`          | `selectionMode` 非 `none` 时切换选中                                                   |
| `Delete` / `Backspace`     | 已监听 `remove` 时移除当前标签；若该项已选中则移除未禁用的选中项                       |
| `Escape`                   | `escapeKeyBehavior` 为 `clearSelection` 且 `disallowEmptySelection` 不为真时清空选中   |
| 字符键                     | 按标签文案快速定位并移动焦点                                                           |

## Examples

### Variants

```vue
<script lang="ts" setup>
import type { TagGroupItem } from '../tag-group.props'
import { ref } from 'vue'
import TagGroup from '../tag-group.vue'

function createItems(): TagGroupItem[] {
  return [
    { label: 'Alpha', value: 'alpha' },
    { label: 'Beta', value: 'beta' },
    { label: 'Gamma', value: 'gamma' },
  ]
}

const softItems = ref(createItems())
const outlineItems = ref(createItems())
const invertedItems = ref(createItems())
</script>

<template>
  <div class="flex flex-col gap-4 max-w-sm w-full">
    <TagGroup variant="soft" :items="softItems" />

    <TagGroup variant="outline" :items="outlineItems" />

    <TagGroup variant="inverted" :items="invertedItems" />
  </div>
</template>
```

### Sizes

```vue
<script lang="ts" setup>
import type { TagGroupItem } from '../tag-group.props'
import { ref } from 'vue'
import TagGroup from '../tag-group.vue'

function createItems(): TagGroupItem[] {
  return [
    { label: 'Small', value: 'sm' },
    { label: 'Medium', value: 'md' },
    { label: 'Large', value: 'lg' },
  ]
}

const smItems = ref(createItems())
const mdItems = ref(createItems())
const lgItems = ref(createItems())
</script>

<template>
  <div class="flex flex-col gap-4 max-w-sm w-full">
    <TagGroup size="sm" :items="smItems" />

    <TagGroup size="md" :items="mdItems" />

    <TagGroup size="lg" :items="lgItems" />
  </div>
</template>
```

### With Icon

```vue
<script lang="ts" setup>
import type { TagGroupItem } from '../tag-group.props'
import { ref } from 'vue'
import TagGroup from '../tag-group.vue'

const items = ref<TagGroupItem[]>([
  {
    label: 'Design',
    value: 'design',
    icon: 'ri:palette-line',
    selectedIcon: 'ri:palette-fill',
  },
  {
    label: 'Code',
    value: 'code',
    icon: 'ri:code-s-slash-line',
    selectedIcon: 'ri:code-s-slash-fill',
  },
  {
    label: 'Docs',
    value: 'docs',
    icon: 'ri:book-open-line',
    selectedIcon: 'ri:book-open-fill',
  },
])
</script>

<template>
  <div class="max-w-sm w-full">
    <TagGroup selection-mode="multiple" :items="items" />
  </div>
</template>
```

### Selection

```vue
<script lang="ts" setup>
import type { TagGroupItem, TagGroupItemValue } from '../tag-group.props'
import { ref } from 'vue'
import TagGroup from '../tag-group.vue'

const singleItems = ref<TagGroupItem[]>([
  { label: 'Low', value: 'low' },
  { label: 'Medium', value: 'medium' },
  { label: 'High', value: 'high' },
])

const multipleItems = ref<TagGroupItem[]>([
  { label: 'Vue', value: 'vue' },
  { label: 'React', value: 'react' },
  { label: 'Svelte', value: 'svelte' },
])

const singleValue = ref<TagGroupItemValue>()
const multipleValue = ref<TagGroupItemValue[]>([])

function onRemoveSingle(values: TagGroupItemValue[]) {
  singleItems.value = singleItems.value.filter((item) => !values.includes(item.value))
}

function onRemoveMultiple(values: TagGroupItemValue[]) {
  multipleItems.value = multipleItems.value.filter((item) => !values.includes(item.value))
}
</script>

<template>
  <div class="flex flex-col gap-4 max-w-sm w-full">
    <TagGroup
      v-model="singleValue"
      selection-mode="single"
      :items="singleItems"
      @remove="onRemoveSingle"
    />

    <TagGroup
      v-model="multipleValue"
      selection-mode="multiple"
      :items="multipleItems"
      @remove="onRemoveMultiple"
    />
  </div>
</template>
```

### Disabled

```vue
<script lang="ts" setup>
import type { TagGroupItem } from '../tag-group.props'
import TagGroup from '../tag-group.vue'

const items: TagGroupItem[] = [
  { label: 'Locked', value: 'locked' },
  { label: 'Read only', value: 'readonly' },
  { label: 'Disabled', value: 'disabled' },
]
</script>

<template>
  <div class="max-w-sm w-full">
    <TagGroup disabled :items="items" />
  </div>
</template>
```

### Unstyled

```vue
<script lang="ts" setup>
import type { TagGroupItem } from '../tag-group.props'
import { ref } from 'vue'
import TagGroup from '../tag-group.vue'

const items = ref<TagGroupItem[]>([
  { label: 'Plain', value: 'plain' },
  { label: 'Custom', value: 'custom' },
  { label: 'Styles', value: 'styles' },
])
</script>

<template>
  <div class="max-w-sm w-full">
    <TagGroup unstyled :items="items" />
  </div>
</template>
```