antd vue 表单与tag结合
时间: 2025-02-24 21:17:34 AIGC 浏览: 85
### Ant Design Vue 表单集成 Tag 组件 示例
为了实现表单与标签(Tag)组件的有效结合,在 Ant Design Vue 中可以利用 `a-form` 和 `a-tag` 这两个核心组件。通过这种方式,不仅能够创建动态输入框让用户添加新的标签,还可以轻松管理和展示已有的标签列表。
#### 动态添加 Tags 到 FormItem
下面是一个简单的例子,展示了如何在一个表单项内嵌入多个标签,并允许用户通过点击按钮或按回车键来增加新标签:
```html
<template>
<a-form :model="formState">
<a-form-item label="Tags" name="tags">
<!-- 显示现有标签 -->
<span v-for="(tag, index) in formState.tags" :key="index">
<a-tag closable @close="handleClose(tag)">
{{ tag }}
</a-tag>
</span>
<!-- 输入新标签 -->
<a-input
ref="inputRef"
v-if="inputVisible && !inputValue.trim()"
type="text"
size="small"
:value="inputValue"
@change="handleChange"
@blur="handleInputConfirm"
@keyup.enter="handleInputConfirm"
/>
<a-button v-else type="primary" @click="showInput">Add</a-button>
</a-form-item>
<!-- 提交按钮 -->
<a-form-item>
<a-button type="primary" html-type="submit" @click.prevent="handleSubmit">
Submit
</a-button>
</a-form-item>
</a-form>
</template>
<script lang="ts">
import { defineComponent, reactive } from 'vue';
export default defineComponent({
setup() {
const formState = reactive({ tags: [] as string[] });
let inputVisible = false;
let inputValue = '';
function handleClose(removedTag: string): void {
const newTags = formState.tags.filter((tag) => tag !== removedTag);
formState.tags = newTags;
}
function showInput(): void {
inputVisible = true;
}
function handleChange(e: Event): void {
inputValue = (e.target as HTMLInputElement).value;
}
function handleInputConfirm(): void {
if (inputValue && !formState.tags.includes(inputValue)) {
formState.tags.push(inputValue);
}
inputVisible = false;
inputValue = '';
}
function handleSubmit(): void {
console.log('Form Submitted:', formState);
}
return {
formState,
inputVisible,
inputValue,
handleClose,
showInput,
handleChange,
handleInputConfirm,
handleSubmit,
};
},
});
</script>
```
此代码片段实现了基本的功能需求:用户可以在表单中添加、删除以及提交带有标签的数据[^1]。
阅读全文
相关推荐

















