使用 Vuelidate 和 Bootstrap Vue 验证模态内的表单

Iag*_*llo 5 validation bootstrap-modal vue.js bootstrap-4

开发人员,我正在使用 Vuejs 并且我在模态中有一个表单,我需要使用vuelidate在客户端验证表单的字段。

我也使用bootstrap-vue来创建模态,但是当我实现验证时,我无法让“取消”按钮一键清除字段和验证。它关闭模态,清理字段,但是当我再次打开它时,字段是红色的,显示验证错误,我必须再次单击取消以清理验证(不想这样做!)。我的模板和脚本如下。

模板

<b-modal
  id="signupFormModal"
  title="Crie a sua conta!"
  ref="modal"
  centered
  @ok="handleOk"
  @cancel="clearForm"
>
  <b-container fluid>
    <b-card>
      <b-form @submit.stop.prevent="handleSubmit">
        <b-form-group
          id="email"
          label-for="email"
        >
          <b-form-input
            ref="focusElement"
            autocomplete="username"
            id="email"
            type="email"
            v-model.trim="form.email"
            :state="$v.form.email.$dirty ? !$v.form.email.$error : null"
            @input="$v.form.email.$touch()"
            required
            placeholder="E-mail"
          />
        <small class="error">{{emailErrors}}</small>
        </b-form-group>
      </b-form>
    </b-card>
  </b-container>
</b-modal>
Run Code Online (Sandbox Code Playgroud)

脚本

import { required, minLength, sameAs, email } from 'vuelidate/lib/validators'

export default {  
name: 'myForm',
  data: () => ({
    form: {
      email: '',
      password: '',
      confirmPassword: ''
    },
    show: true,
    nameState: null
  }),
  validations: {
    form: {
      email: { required, email },
      password: {
        required,
        minLength: minLength(6)
      },
      confirmPassword: {
        required,
        sameAsPassword: sameAs('password')
      }
    }
  },
  computed: {
emailErrors () {
  if (!this.$v.form.email.$dirty) {
    this.returnNull()
    return ''
  } else if (!this.$v.form.email.required) {
    this.returnFalse()
    return 'E-mail é obrigatório'
  } else if (!this.$v.form.email.email) {
    this.returnFalse()
    return 'Exemplo: exemplo@exemplo.com'
  } else {
    this.returnNull()
  }
}
  },

methods: {
    clearForm () {
      /* Reset our form values */
      this.form.email = ''
      this.form.password = ''
      this.form.confirmPassword = ''
      this.$v.$reset()
    },
handleOk (evt) {
  // Prevent modal from closing
  evt.preventDefault()
  if (!this.$v.invalid) {
    this.handleSubmit()
  } else {
    this.$v.touch()
  }
},

handleSubmit () {
  console.log(JSON.stringify(this.form))
  this.clearForm()
  this.$refs.modal.hide()
},

focusMyElement (e) {
  this.$refs.focusElement.focus()
},

returnNull () {
  this.nameState = null
},
returnFalse () {
  this.nameState = false
},
returnTrue () {
  this.nameState = null
}
  }
}
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决这个问题?我现在处于这个困境2天了。

提前感谢帮助。

Noe*_*pez 3

在您的clearForm方法中,只需将对$reset()的调用替换为:

this.$nextTick(() => { this.$v.$reset(); })
Run Code Online (Sandbox Code Playgroud)

在某些情况下,您需要在 DOM 更新和数据更改后调用$reset() ,这是通过nextTick实现的