Search code examples
javascriptvue.jsvuex

Vue modal diaglog with child form, submit data


Wireframe

The black boundary is a modal component, the red is a component which has some form fields. The buttons, save / cancel are based in the parent modal component. The form is actually 2 levels down from the modal (modal component -> child wrapper -> child form) so vuex feels a better choice.

There is also a file picker in the form.

What is the best way to get the data from the component (which could be one of a number of forms) when a user clicks the Save button.

option 1 - on each field change, call a method to update data in VUEX.
option 1a - update an object on each field change containing the whole form
option 1b - update each field individually on change.
option 2 - use refs to call some sort of submit method in child.
option 3 - a better way than 1 or 2!

issues

  • option 1a, as I am passing the "data" object into vuex, when another change is made, the form is updating the v-model but it is in vuex so it is mutated outside of the mutation.
  • option 1b seems a lot of work to get lots of field mapped into vuex.
  • option 2 since there are 2 levels of components, (which swap out) the refs seems clunky

Solution

  • You can use a computed setter to avoid mutating outside of the mutation.

    computed: {
        fieldOne: {
            get () {
                return this.$store.state.data.fieldOne
            },
            set (newValue) {
                this.$store.commit('data/fieldOne', newValue)
            }
        }
    
    }
    

    Alternatively, you might use :value and @input instead of v-model

        <input
          :value="$store.state.data.fieldOne"
          @input="$store.commit('data/fieldOne', $event.target.value)"
        >