在 Vue 中使用 Vuelidate 的验证不起作用

Validations in Vue using Vuelidate are not working

大家好

我想知道我是否遗漏了什么,我想了几个小时但没有找到解决方案。

我正在尝试在 vue 中使用 Vuelidate 进行表单验证,一切似乎都已到位,但在我创建自定义警报之后,表单仍在进入下一阶段。

我这样声明 Vuelidate:

import useVuelidate from '@vuelidate/core'
import { required } from '@vuelidate/validators'

Inside Data() 我做了如下操作:

data: () => ({
    v$: useVuelidate(),
    currentStage: 1,
    traffic: {
      unique: '',
      unique1: '',
      unique2: '',
      unique3: '',
      unique4: ''
    },
  }),

在 data() 之外声明验证,如下所示:

validations() {
    return {
      traffic: {
        unique1: { required },
        unique2: { required },
        unique3: { required },
        unique4: { required },
        unique5: { required }
      },
    }
  },

最后一件事是计算,我的功能是在表单的第 3 阶段创建输入字段:

  computed: {

        appendFields() {
          this.v$.$validate()
          if(!this.v$.$error){
            if(this.jsonStatham.hasOwnProperty(this.traffic.unique1)){
              this.integrationParams.push(...Object.keys(this.jsonStatham[this.traffic.unique1]))
            }
          } else {
            alert("Error, Not all fields are filled in.")
          }
        }
      },

所以这就是问题所在,当调用 appendFields() 时,我确实收到此警报:alert("Error, Not all fields are filled in.") 但是在我按警报中的“确定”后,表格仍在进入下一阶段。 我错过了什么?

编辑: 这是执行“appendFields”方法的按钮:

<button @click="buttonClicked(0); appendFields;">Next Stage</button>

这是 buttonClicked 函数:

 buttonClicked(value) {
      if(value === 0){
        this.currentStage++;
        return this.currentStage;
      }
      if(value === 1){
        this.currentStage--;
        return this.currentStage;
      }
    },

click-处理程序更新 currentStage 而不首先验证表单。但是,验证发生在 appendFields 中,它是在 buttonClicked() 之后计算的。验证应该是第一步,它可以阻止后续步骤。

我会这样重构它:

  1. 使 appendFields 成为组件 method,因为它并不是真正的计算 属性(特别是因为它 returns 什么都没有)。

  2. 为了清楚起见,将 currentStage 更新移到它自己的函数中。

  3. 将表单验证从 appendFields() 移至按钮的 click-处理程序。

  4. click-handler 中,如果表单有效,则调用在步骤 1 和 2 中创建的函数。

export default {
  methods: {
    // 1️⃣
    appendFields() {
      if (this.jsonStatham.hasOwnProperty(this.traffic.unique1)) { 
this.integrationParams.push(...Object.keys(this.jsonStatham[this.traffic.unique1]))
      }
    },
    // 2️⃣
    updateStage(value) {
      if (value === 0) {
        this.currentStage++
      } else if (value === 1) {
        this.currentStage--
      }
    },
    buttonClicked(value) {
      // 3️⃣
      this.v$.$validate()

      if (!this.v$.$error) {
        // 4️⃣
        this.appendFields()
        this.updateStage(value)

      } else {
        alert("Error, Not all fields are filled in.")
      }
    }
  }
}

还要注意useValidate() is intended for the Composition API,所以应该在setup()里面调用:

export default {
  setup() {
    return {
      v$: useValidate()
    }
  }
}