重置后Vuetify表单验证错误

时间:2019-02-20 15:46:10

标签: vue.js vuetify.js

我在组件内部具有以下内容:

<v-form v-model="valid" ref="form" class="px-3">
  <v-text-field label="First Name" v-model="firstname" :rules="inputRules"></v-text-field>
  <v-text-field label="Last Name" v-model="lastname" :rules="inputRules"></v-text-field>
  <v-text-field label="Email" v-model="email"></v-text-field>
  <v-btn :loading="loading" flat class="success mx-0 mt-3" @click="submit">Create Person</v-btn>
</v-form>

脚本:

export default {
  data() {
    return {
      valid: true,
      firstname: '',
      lastname: '',
      email: '',
      loading: false,
      dialog: false,
      inputRules: [
        v => v.length >= 2 || 'Minimum length is 2 characters'
      ]
    }
  },
  methods: {
    submit() {
      if(this.$refs.form.validate()) {
        this.loading = true;

        const person = {
          firstname: this.firstname,
          lastname: this.lastname,
          email: this.email
        };

        sendToMyDB(person).then(()=>{
          this.loading = false;
          this.dialog = false;
          this.$refs.form.reset();
        })
      }
    }
  }
}

因此,我将表单数据提交到我的数据库,然后成功地使用了this。$ refs.form.reset();重置我的表单。

但是,在随后的每个提交中,我都会立即收到错误消息:

  

“ [Vue警告]:nextTick中的错误:” TypeError:无法读取属性   “长度”未定义”

  

TypeError:无法读取未定义的属性“ length”

1 个答案:

答案 0 :(得分:0)

Vuetify将undefined传递给inputRules中引用的功能。您可以看到它读取了堆栈调用:

call stack

我建议您在访问v的内容之前先对其进行测试:

undefined

v => (v && v.length >= 2) || 'Minimum length is 2 characters' 

取决于您的业务规则。

v => (!v || v.length >= 2) || 'Minimum length is 2 characters'
var app = new Vue({
  el: '#app',
  data() {
    return {
      valid: true,
      firstname: '',
      lastname: '',
      email: '',
      loading: false,
      dialog: false,
      inputRules: [
        v => (v && v.length >= 2) || 'Minimum length is 2 characters'
      ]
    }
  },
  methods: {
    submit() {
      if (this.$refs.form.validate()) {
        this.loading = true;

        const person = {
          firstname: this.firstname,
          lastname: this.lastname,
          email: this.email
        };

        /* sendToMyDB(person) */
        Promise.resolve().then(() => {
          this.loading = false;
          this.dialog = false;
          this.$refs.form.reset();
        })
      }
    }
  }
});