Reset Vuetify form validation

℡╲_俬逩灬. 提交于 2020-12-04 15:11:23

问题


I have trouble resetting vuetify validation in v-dialog.

This codepen is the simplified version of what I have.
https://codepen.io/yuukive/pen/BVqpEZ

With the code above, if I do

(Open dialog --> press SAVE button --> (validation fails) --> press CLOSE button --> open dialog again),

it is already validated when I open the dialog again...

Is it possible to reset validation before a user opens it the 2nd time?

new Vue({
  el: '#app',
  data: () => ({
    dialog: false,
    emailRules: [v => !!v || 'Name is required']
  }),
  methods: {
    onSave() {
      if (!this.$refs.form.validate()) return
      dialog = false
    }
  }
})
<div id="app">
  <v-app id="inspire">
    <v-layout row justify-center>
      <v-dialog v-model="dialog" persistent max-width="500px">
        <v-btn slot="activator" color="primary" dark>Open Dialog</v-btn>
        <v-card>
          <v-card-title>
            <span class="headline">Email</span>
          </v-card-title>
          <v-form ref="form">
            <v-card-text>
              <v-container grid-list-md>
                <v-layout wrap>
                  <v-flex xs12>
                    <v-text-field label="Email" required :rules="emailRules"></v-text-field>
                  </v-flex>
                </v-layout>
              </v-container>
              <small>*indicates required field</small>
            </v-card-text>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="blue darken-1" flat @click.native="dialog = false">Close</v-btn>
              <v-btn color="blue darken-1" flat @click.native="onSave">Save</v-btn>
            </v-card-actions>
          </v-form>
        </v-card>
      </v-dialog>
    </v-layout>
  </v-app>
</div>

回答1:


Example from docs uses:

this.$refs.form.reset()

Note that while reset() clears validation, it clears input as well.
You can follow this issue to see further updates on this.

So you can perhaps watch dialog value and reset the form:

watch: {
    dialog() {
        this.$refs.form.reset()
    }
}



回答2:


resetValidation() will clear validation errors only, reset() will also clear input fields.




回答3:


this.$refs.form.reset() might work on JavaScript, but compiler for TypeScript complains about typing. Even though during serve you can only see errors in the terminal without breaking the app, it'll actually break when you'll try to build the app.

Creating a new variable and assigning into it any type does the trick, below an example:

const refForm: any = this.$refs.form;
refForm.reset();


来源:https://stackoverflow.com/questions/51059402/reset-vuetify-form-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!