2022-08-19

create update form with v-model and data come to state vue2

I have a form that I want to pre-fill to update my users' information. The data comes from the state (vuex) and is retrieved from my API so it is asynchronous.

How can I pre-fill the form with the data when it is only available a few seconds after the form is loaded?

For the example Here is the behavior of my form:

var app = new Vue({
  el: '#app',
  data: {
    firstname: null,
    lastname: null,
    stateFirstname: null,
    stateLastname: null,
  },
  methods: {
    submitForm() {
      // send form data to my API
      console.log(this.firstname, this.lastname);
    }
  },
  mounted () {
    // Data in state come from my API and is async 
    // I simulate here its behavior
    setTimeout(() => {
        this.stateFirstname = "John";
      this.stateLastname = "Doe";
    }, 3000)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <form @submit.prevent="submitForm">
    <label for="firstname">Firstname</label>
    <input v-model="firstname" id="firstname" />
    <label for="lastname">Lastname</label>
    <input id="lastname" />
    <button type="submit">UPDATE</button>
  </form>
</div>

I have tested things that seem to work but are not clean like using a watcher on each data but it doesn't seem clean as a way to do it. What is the best solution ?



No comments:

Post a Comment