我正在使用Nuxt3表单,当我单击添加/删除按钮时,需要添加或删除输入字段.
例如,我有3个输入域:"Place1、Place2、Place3"和一个用于提交表单的按钮.
如果我点击"添加"按钮,我想添加一个新的域"Place4"、"Place5"等等. 此外,当我单击删除按钮时,可能需要删除所有输入字段.
有没有办法动态调整输入栏?
谢谢.
为此,我使用了v-for语句,当我添加输入字段时,它具有相同的值. 但是每个输入域应该有不同的值.
我正在使用Nuxt3表单,当我单击添加/删除按钮时,需要添加或删除输入字段.
例如,我有3个输入域:"Place1、Place2、Place3"和一个用于提交表单的按钮.
如果我点击"添加"按钮,我想添加一个新的域"Place4"、"Place5"等等. 此外,当我单击删除按钮时,可能需要删除所有输入字段.
有没有办法动态调整输入栏?
谢谢.
为此,我使用了v-for语句,当我添加输入字段时,它具有相同的值. 但是每个输入域应该有不同的值.
您可以使用这些代码来实现这一点.
<script setup lang="ts">
const places = ref(['', '', ''])
const addField = () => {
places.value.push('')
}
const formRef = ref<HTMLFormElement | null>(null)
const removePlace = (index: number) => {
places.value.splice(index, 1)
}
const submitForm = () => {
if (formRef.value) {
const formData = new FormData(formRef.value)
for (const [fieldName, fieldValue] of formData.entries()) {
console.log(`${fieldName} :`, fieldValue)
}
formRef.value.reset()
}
}
</script>
<template>
<div>
<form
@submit.prevent="submitForm"
ref="formRef"
>
<div
v-for="(place, index) in places"
:key="index"
style="margin-bottom: 10px;"
>
<label>Place {{ index + 1 }}</label>
<div>
<input
type="text"
:placeholder="`Place${index + 1}`"
:name="`place${index + 1}`"
/>
<button
type="button"
@click="removePlace(index)"
>Remove</button>
</div>
</div>
<div style="display: flex; gap: 10px;">
<button
type="button"
@click="addField"
>
Add Field
</button>
<button type="submit">Submit</button>
</div>
</form>
</div>
</template>
<style></style>
经过测试,它起作用了!