我目前正在学习前端javascript开发,目前正在使用VueJS、Vuetify和VueJS进行一个个人项目。
我有个简单的问题。
我有两个文本字段如下。
<v-layout wrap>
<v-flex>
<v-text-field
label="First Name"
maxlength="20"
v-model.trim="firstName"
:error-messages="firstNameErrors"
@input="$v.firstName.$touch()"
@blur="$v.firstName.$touch()"
></v-text-field>
</v-flex>
<v-flex>
<v-text-field
label="Last Name"
v-model.trim="lastName"
maxlength="20"
:error-messages="lastNameErrors"
@input="$v.lastName.$touch()"
@blur="$v.lastName.$touch()"
></v-text-field>
</v-flex>
</v-layout>我在计算钩子中写了一个vuelidate,如下所示。
computed: {
firstNameErrors () {
const errors = []
if (!this.$v.firstName.$dirty) return errors
!this.$v.firstName.required && errors.push('First Name is required')
return errors
},
lastNameErrors () {
const errors = []
if (!this.$v.lastName.$dirty) return errors
!this.$v.lastName.required && errors.push('Last Name is required')
return errors
}代码运行良好,并完成了应该做的事情,生成验证错误,在我的例子中是“必需的”。
我的问题是,我希望将验证错误函数"firstNameErrors“和"lastNameErrors”都包含在一个名为"requiredErrors“的函数中,而不是有两个单独的函数。
代码笔:https://codepen.io/pen/jebLgM
任何帮助都是非常感谢的。
谢谢。
发布于 2018-10-02 10:05:48
我不遵循你的逻辑,但从字面上看,你的请求可能如下所示:
<v-layout wrap>
<v-flex>
<v-text-field
label="First Name"
maxlength="20"
v-model.trim="firstName"
:error-messages="requiredErrors"
@input="$v.firstName.$touch()"
@blur="$v.firstName.$touch()"
></v-text-field>
</v-flex>
<v-flex>
<v-text-field
label="Last Name"
v-model.trim="lastName"
maxlength="20"
:error-messages="requiredErrors"
@input="$v.lastName.$touch()"
@blur="$v.lastName.$touch()"
></v-text-field>
</v-flex>
</v-layout>
computed: {
requiredErrors () {
const errors = []
this.$v.firstName.$dirty
&& !this.$v.firstName.required
&& errors.push('First Name is required')
this.$v.lastName.$dirty
&& !this.$v.lastName.required
&& errors.push('Last Name is required')
return errors
}更新
是的,这就是为什么我说我不遵循你的逻辑(对于两个输入都有相同的信息)。您可能可以使用不同的第一个参数多次通过bind-ing实现所需的功能,但是函数不能再是组件的方法(因为这些方法已经被Vue绑定了)。
也许是这样的:
<v-text-field
label="First Name"
maxlength="20"
v-model.trim="firstName"
:rules="requiredErrorsFirstName"
@input="$v.firstName.$touch()"
@blur="$v.firstName.$touch()"
></v-text-field>
<v-text-field
label="Last Name"
v-model.trim="lastName"
maxlength="20"
:rules="requiredErrorsLastName"
@input="$v.lastName.$touch()"
@blur="$v.lastName.$touch()"
></v-text-field>
computed:
{
requiredErrorsFirstName ()
{
return [requiredErrors.bind(this,'firstName')];
},
requiredErrorsLastName ()
{
return [requiredErrors.bind(this,'lastName')];
}
}
function requiredErrors(fieldName, fieldValue)
{
switch(fieldName)
{
case 'firstName':
return this.$v[fieldName].$dirty
&& !this.$v[fieldName].required
? 'First Name is required' : true;
case 'lastName':
return this.$v[fieldName].$dirty
&& !this.$v[fieldName].required
? 'Last Name is required' : true;
}
}我个人认为,这是丑陋的,并希望有一个单独的计算属性或每个字段的方法。
https://stackoverflow.com/questions/52605296
复制相似问题