Search code examples
vue.jsvuejs2vue-componentvuetify.js

Best way to clear a dialogs form after submit or close of the dialog


Below I show the parent vue which contains a dialog+form for adding a new record, in this case a user. When the form is cancelled, I would like input fields to be cleared, which in this case I am using v-model to tie those fields to a user template in the data method.

I would like to control this from the parent, as this is where calls to API are taking place, and if there is an error on save, i would like to retain the dialog form and present the error message, otherwise I would just clear the form on the dialog for button clicks.

Have looked at quite a few examples, and all seem to be wonky. Seems this should be simple enough but I have yet to figure out.

Parent vue

...
<AddUser
    :visible="isAddDialogVisible"
    :error="error"
    v-on:onConfirmed="onAddUserConfirmed"
    v-on:onCancelled="onAddUserCancelled"
/>
...
onAddClick: function() {
    this.isAddDialogVisible = true;
}
...
onAddUserCancelled () {
    this.isAddDialogVisible = false;
}

Dialog component

data() {
  return {
    user: {}
  }
},
props: {
  error: {},
  visible: {
    type: Boolean,
    default: false,
  }
},
...
onCancel() {
  this.$emit("onCancelled");
}

Solution

  • Maybe the best and shortest way would be to do it with v-if:

    <AddUser
        v-if="isAddDialogVisible"
        :visible="isAddDialogVisible"
        :error="error"
        v-on:onConfirmed="onAddUserConfirmed"
        v-on:onCancelled="onAddUserCancelled"
    />
    

    It will completely destroy dialog when false and re-render it when true.