Search code examples
vue.jsvuelidate

Vue - how to validate data from Vuex store


I have a rather big form which I post to an API backend. The form has about 17-20 fields, depending on the status of a checkbox.

My plan is that after the user fills out the form I will validate it using Vuelidate and then display a summary of the data to give the user the possibility of reviewing their data. After the user reviews the data and considers that is correct, it posts the form to the backend API.

To do this, I plan on using Vuex to store the form object, and use the store to display the fields in the form and also on the summary page.

Is this a good approach, to store the form object in Vuex? If so, where I define the validation rules in store.js? Thank you very much for your feedback!


Solution

  • You don't really need Vuex for this. You can keep your form validation rules in your component itself. If you have something of a form builder or a different component that takes care of your form, you can keep your validation rules there or accept the entire form model through prop from the Component where you want to use the form.

    Once the submission is done, you can pass the data to your Summary page via route itself. Check this out - https://router.vuejs.org/guide/essentials/passing-props.html

    Whenever you think about Vuex or any state management solution think about the lifecycle of that data. How long is it needed to persist. In most cases, you'll find that it belongs to one view or two.

    Vuex is good for cases where you need a piece of data to persist for way longer, possibly entire duration of the app. Example - User Details, Theme Settings, Experience Configuration etc.

    Let me know how it goes.