如何将 vuelidate 与 vuetify 2 一起用于嵌套数据?获取无效字段

How to use vuelidate with vuetify 2 for nested data? Getting invalid field

我正在尝试将 vuelidate 与 Vuetify 2 一起使用,但我在尝试验证嵌套对象值时遇到了麻烦。

这段代码工作正常:

    <template>
        <v-text-field
        v-model="no_nome"
        :error-messages="nameErrors"
        label="Nome"
        @input="$v.no_nome.$touch()"
        @blur="$v.no_nome.$touch()"
        >
        </v-text-field>
    </template>

    <script>

     import { required } from 'vuelidate/lib/validators'
     export default {

        data() {
            return {
                no_nome:'',
            }
        },
        validations: {
            no_nome: {
                required
            },
        },
        computed: {
            nameErrors () {
                const errors = []
                if (!this.$v.no_nome.$dirty)
                    return errors
                !this.$v.no_nome.required && errors.push('Name is required.')
                return errors
            },
        }
     }
   </scrip>

但是如果我将 no_nome 数据更改为:

        data() {
            return {
                user : {
                   no_nome:'',
                }
            }
        },

        <v-text-field
        v-model="user.no_nome"
        :error-messages="nameErrors"
        label="Nome"
        @input="$v.no_nome.$touch()"
        @blur="$v.no_nome.$touch()"
        >
        </v-text-field>

在 运行 $vm0.$v.no_nome.$touch() 之后,$vm0.$v.no_nome.$invalid 将始终 return true 即使 user.no_nome 不为空。我怎样才能使验证适用于 user.no_nome 和任何其他嵌套数据值?

您必须在数据和验证之间使用相同的数据形状。参见 Data Nesting

所以你的 validations 必须是:

validations: {
  user: {
    no_nome: {
      required
    }
  }
}

computed: {
  nameErrors () {
    const errors = []
    if (!this.$v.user.no_nome.$dirty)
      return errors
    !this.$v.user.no_nome.required && errors.push('Name is required.')
    return errors
  }
}

<v-text-field
  v-model="user.no_nome"
  :error-messages="nameErrors"
  @input="$v.user.no_nome.$touch()"
  @blur="$v.user.no_nome.$touch()"/>

Example