Half_Duplex
Half_Duplex

Reputation: 5234

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");
}

Upvotes: 2

Views: 4184

Answers (2)

KorbenDose
KorbenDose

Reputation: 1263

A little late, but there's another solution. For me, the v-if solution removed the dialog's closing animations.

Instead, you can use key and give it a new value each time the dialog is openend. Changing the key will force the component to re-render and reset its internal state.

<AddUser
    :key="key"
    :visible="isAddDialogVisible"
/>


<script setup>
// imports ...

const isAddDialogVisible = ref(false);
let key;

function onAddClick() {
    isAddDialogVisible.value = true;
    key = Date.now() // use anything here that changes the value
}

// ...
</script>

Upvotes: 0

N. Djokic
N. Djokic

Reputation: 1046

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.

Upvotes: 7

Related Questions