Home > Mobile >  Default the data object to a model back to mounted value
Default the data object to a model back to mounted value

Time:11-19

I've begun tinkering with Vue and Vuetify a bit, the framework is pretty stellar. But one issue I appear to of encountered is if I have an object:

account: {
     name: "",
     customer: {
         orders: []
     }
}

When Vue binds the model, the object adheres to those values. But if I close a form I have to manually set a value back to the default, to ignore the bound message.

this.account.name = "";

To default the value back to when the component was mounted seems, a bit wonky. Is there a way to default the data back to the mounted state without forcing the component to re-render?

CodePudding user response:

One way to do this is to define a function outside the component to return the data. The latter would be used as initial value and when resetting:

const getDefaultData = () => ({ account: { name: "", customer: { orders: [] } } });

new Vue({
  el: "#app",
  data: getDefaultData,
  methods: { reset() { Object.assign(this.$data, getDefaultData()); } }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div>{{account}}</div>
  <form><input v-model="account.name" /></form>
  <button @click="reset">Reset</button>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related