使用 Vee-validate 禁用按钮,直到正确填写表单 [英] Using Vee-validate to disable button until form is filled out correctly

查看:27
本文介绍了使用 Vee-validate 禁用按钮,直到正确填写表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的表单填写正确之前禁用我的提交按钮,这是我目前所拥有的:

I want to disable my submit button until my form is filled out correctly, this is what I have so far:

<form>
   <input type="text" class="form-control" v-validate="'required|email'" name="email" placeholder="Email" v-model="userCreate.userPrincipalName" />
   <span v-show="errors.has('email')">{{ errors.first('email') }}</span>
   <button v-if="errors.any()" disabled="disabled" class="btn btn-primary" v-on:click="sendInvite();" data-dismiss="modal" type="submit">Send Invite</button>
   <button v-else="errors.any()" class="btn btn-primary" v-on:click="sendInvite();" data-dismiss="modal" type="submit">Send Invite</button>
</form>

以上仅在我开始输入值后打印错误消息并禁用我的提交按钮.在我开始与输入交互之前,我需要从一开始就禁用它,这样我就不能发送空字符串.

The above only prints an error message and disables my submit button after I've started inputting a value. I need it to be disabled from the start, before I start interacting with the input, so that I cannot send an empty string.

另一个问题是,是否有比使用 v-if 更好的方法来做到这一点?

Another question is if there is a better way than using v-ifto do this?

 userCreate: {
        customerId: null,
        userPrincipalName: '',
        name: 'unknown',
        isAdmin: false,
        isGlobalAdmin: false,
        parkIds: []
    }

推荐答案

禁用按钮直到所有你需要的值都被填满的一种方法是使用一个计算属性,如果所有值都被赋值或不赋值,该属性将返回 bool

One way to disable a button until all the values you need are filled, is to use a computed property that will return bool if all values are assigned or not

示例:

像这样创建一个计算属性:

Create a computed property like this:

computed: {
  isComplete () {
    return this.username && this.password && this.email;
  }
}

并将其绑定到 html disabled 属性为:

And bind it to the html disabled attribute as:

<button :disabled='!isComplete'>Send Invite</button

这意味着,如果 !isComplete 为真,则禁用按钮

This means, disable the button if !isComplete is true

此外,在您的情况下,您不需要两个 if/else 绑定按钮.您可以根据表单是否完成使用一个来隐藏/显示它:

Also, in your case you don't need two if/else-bound buttons. You can use just one to hide/show it based on if the form is completed or has any errors:

<button :disabled="errors.any() || !isCompleted" class="btn btn-primary" v-on:click="sendInvite();" data-dismiss="modal" type="submit">Send Invite</button>

此按钮将被禁用,直到所有字段都已填写且未发现错误

This button will be disabled until all fields are filled and no errors are found

这篇关于使用 Vee-validate 禁用按钮,直到正确填写表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆