gpt4 book ai didi

vue.js - 重置后 Vuetify 表单验证错误

转载 作者:行者123 更新时间:2023-12-02 14:52:39 27 4
gpt4 key购买 nike

我在组件中有以下内容:

<v-form v-model="valid" ref="form" class="px-3">
<v-text-field label="First Name" v-model="firstname" :rules="inputRules"></v-text-field>
<v-text-field label="Last Name" v-model="lastname" :rules="inputRules"></v-text-field>
<v-text-field label="Email" v-model="email"></v-text-field>
<v-btn :loading="loading" flat class="success mx-0 mt-3" @click="submit">Create Person</v-btn>
</v-form>

脚本:

export default {
data() {
return {
valid: true,
firstname: '',
lastname: '',
email: '',
loading: false,
dialog: false,
inputRules: [
v => v.length >= 2 || 'Minimum length is 2 characters'
]
}
},
methods: {
submit() {
if(this.$refs.form.validate()) {
this.loading = true;

const person = {
firstname: this.firstname,
lastname: this.lastname,
email: this.email
};

sendToMyDB(person).then(()=>{
this.loading = false;
this.dialog = false;
this.$refs.form.reset();
})
}
}
}
}

所以我将表单数据提交到我的数据库然后在成功 promise 中我使用 this.$refs.form.reset();重置我的表单。

但是,我在每次后续提交时都会立即收到错误消息:

"[Vue warn]: Error in nextTick: "TypeError: Cannot read property 'length' of undefined"

TypeError: Cannot read property 'length' of undefined

最佳答案

Vuetify 正在将 undefined 传递给 inputRules 中引用的函数。您可以看到它读取堆栈调用:

call stack

我建议您在访问其内容之前测试 v 是否为 undefined:

v => (v && v.length >= 2) || 'Minimum length is 2 characters' 

v => (!v || v.length >= 2) || 'Minimum length is 2 characters'

取决于您的业务规则。

var app = new Vue({
el: '#app',
data() {
return {
valid: true,
firstname: '',
lastname: '',
email: '',
loading: false,
dialog: false,
inputRules: [
v => (v && v.length >= 2) || 'Minimum length is 2 characters'
]
}
},
methods: {
submit() {
if (this.$refs.form.validate()) {
this.loading = true;

const person = {
firstname: this.firstname,
lastname: this.lastname,
email: this.email
};

/* sendToMyDB(person) */
Promise.resolve().then(() => {
this.loading = false;
this.dialog = false;
this.$refs.form.reset();
})
}
}
}
});
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuetify/dist/vuetify.min.js"></script>

<div id="app">
<v-form v-model="valid" ref="form" class="px-3">
<v-text-field label="First Name" v-model="firstname" :rules="inputRules"></v-text-field>
<v-text-field label="Last Name" v-model="lastname" :rules="inputRules"></v-text-field>
<v-text-field label="Email" v-model="email"></v-text-field>
<v-btn :loading="loading" text class="success mx-0 mt-3" @click="submit">Create Person</v-btn>
</v-form>
</div>

关于vue.js - 重置后 Vuetify 表单验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54790194/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com