How To Properly Initialize Form Data In Vue How To Properly Initialize Form Data In Vue vue.js vue.js

How To Properly Initialize Form Data In Vue


If you only need to assign store values to your form once then you can use mounted function.

mounted: function() {   this.id = this.$store.state.workflow.id   this.workflow = this.$store.state.workflow.workflow   this.statuses = this.$store.state.workflow.statuses},data() {      return {          workflowData: {              id: '',              workflow: '',              statuses: '',              newStatuses: []          },          workflowLoaded: false      } },


the data property does not accept this, I usually use arrow function in this question because it prohibits me from using this, and prohibits my team from also using this within the data.Declare all necessary items within the datato maintain reactivity, and assign the value within the mounted of the page.

mounted() {   this.workflowData.id = this.$store.state.workflow.id   this.workflowData.workflow = this.$store.state.workflow.workflow   this.workflowData.statuses = this.$store.state.workflow.statuses},data: () => ({   workflowData: {                id: '',                workflow: '',                statuses: '',                newStatuses: []            },            workflowLoaded: false        }    },})


The way how I resolved this problem turned out to be simpler than most of the solutions presented here. I found it hard to reach data from this.$store.state due to Vuejs life cycle. And assigning values to v-mode tourned out to be impossible because "v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth."

Solution

To pre-fill the field with data received from ajax request e.g. input field of type email I did as follow.

1st. I saved the output of my ajax request in application's storage (Cookies) -it can be Local Storage or Session, depended what is appropriate to you.

2nd. I populated my Vuex's store (single source of truth) with the data from my application storage. I do it every time when I reload a page.

3rd. Instead of binding a data to v-model in Vuejs life cycle, or using value attribute of html input (<input type="email" value="email@example.com">). I Pre-filled input by populating placeholder attribute of html with data coming from Vuex store like this:

<input v-model="form.input.email" type="email" name="email" v-bind:placeholder="store.state.user.data.email">