Vuelidate 动态添加一个字段到数组会立即使其变脏

问题描述 投票:0回答:1

我正在开发一个带有

vue 3
vuelidate next
应用程序,并且有一些如下所示的验证:

validations: {
    currentUser: {
        name: {
            required,
            maxLength: maxLength(64),
        },
        email: {
            required,
            email,
            maxLength: maxLength(64),
        },
        address: {
            maxLength: maxLength(191),
        },
        password: {
            minLength: minLength(8),
            maxLength: maxLength(64),
        },
        alarm_emails: {
            $each: helpers.forEach({
                alarm_email: {
                    required,
                    email,
                    maxLength: maxLength(64),
                }
            })
        },
        phones: {
            $each: helpers.forEach({
                number: {
                    required,
                    phone,
                }
            })
        }
    },
},

单击按钮后,我将使用以下代码添加一个新字段:

this.currentUser.alarm_emails.push({alarm_email: '', is_alarm: this.currentUser.is_email_alarm });

这可行,但问题是新字段立即变脏,我不希望这样。

我已经用谷歌搜索了一段时间,但一无所获。我试过:

this.v$.currentUser.$reset();

和类似的事情,但这没有帮助。我什至问过

bard
这件事。

有什么想法吗?

javascript vue.js validation vuejs3 vuelidate
1个回答
0
投票

添加该字段后,您可以手动重置该字段的验证状态。您可以通过以下方式修改代码来实现此目的:

this.currentUser.alarm_emails.push({ alarm_email: '', is_alarm: this.currentUser.is_email_alarm });

// Manually reset validation state for the newly added field
const newAlarmEmailIndex = this.currentUser.alarm_emails.length - 1;
this.$nextTick(() => {
    this.$v.currentUser.alarm_emails[newAlarmEmailIndex].$reset();
});

this.$nextTick()
用于确保在添加新字段后重置其验证状态之前 DOM 已更新。这样,新添加的字段就不会立即被标记为脏。

© www.soinside.com 2019 - 2024. All rights reserved.