在 Vue 3 的 <script setup>
中处理表单验证和必填项时,可以使用 v-model
来双向绑定数据,并确保在用户手动输入后进行校验。根据你提供的代码,若要解决“手动输入之后必填校验仍然展示”的问题,可以考虑以下几个方面:
1. 确保 v-model 的正确使用
确保你的 v-model
是针对每个输入框的数据模型(例如 item.productName
和 item.loanInfoCode[index]
)。如果有多个产品行,确保它们都能正确更新。
2. 使用 watch 监听数据变化
可以通过使用 Vue 的 watch
API 来监听产品名称和借据号的变化,以便及时更新其状态,从而避免必填校验错误。
示例代码修改
以下是调整后的代码示例,包括如何使用 watch
来监听字段的变化并更新验证状态:
<template>
<div
class="loanInfo"
:style="isCustomerNotFound && productRows.length > 0 ? { height: '100px' } : {}"
v-if="!isEditing"
>
<a-row v-if="isCustomerNotFound" v-for="(item, index) in productRows" :key="index">
<a-col :span="12">
<a-form-item
label="产品名称"
name={`productName-${index}`}
:rules="[{
required: true,
message: '请手动输入产品名称!',
validator: (rule, value) => {
return !!value || Promise.reject(new Error('请手动输入产品名称!'));
}
}]"
style="width: 101%"
>
<a-input v-model:value="item.productName" />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item
label="借据号"
name={`loanInfoCode-${index}`}
:rules="[{
required: true,
message: '请手动输入借据号!',
validator: (rule, value) => {
return !!value || Promise.reject(new Error('请手动输入借据号!'));
}
}]"
style="width: 102%; margin-left: -5px"
>
<a-input v-model:value="item.loanInfoCode" />
</a-form-item>
</a-col>
</a-row>
<span
v-if="productRows.length > 0 && isCustomerNotFound"
class="jiahao"
@click="addProductRow"
>
+ 添加产品
</span>
</div>
</template>
<script setup>
import { ref, watch } from 'vue';
const isCustomerNotFound = ref(true);
const productRows = ref([{ productName: '', loanInfoCode: '' }]);
const formModal = ref({});
const modalType = ref('');
const isModalVisible = ref(false);
const handleSubmit = async () => {
try {
await formRef.value.validate();
const values = { ...formModal.value };
if (modalType.value === 'add') {
addCustomer(values);
} else if (modalType.value === 'edit') {
editCustomer(values);
}
setTimeout(() => {
QueryTab();
isModalVisible.value = false;
}, 200);
} catch (error) {
console.error('Validation failed:', error);
}
};
// Watcher to check for manual input and revalidate
watch(productRows, (newValue) => {
// This logic can be customized based on the validation need.
newValue.forEach((item, index) => {
if (!item.productName || !item.loanInfoCode) {
// Trigger any necessary UI updates or state changes here.
}
});
});
// Example method to add a new product row
const addProductRow = () => {
productRows.value.push({ productName: '', loanInfoCode: '' });
};
</script>
核心点总结:
- 确保每个表单项都有唯一的
name
属性,防止冲突。 - 在规则中定义自定义验证函数以动态检查值。
- 使用
watch
函数来监测数据变化并根据需要触发验证或其他逻辑。
内容由零声教学AI助手提供,问题来源于学员提问