2
votes

I'm trying to build

An application that renders a form, where the default input values are equal to the data from the store.

When the save button is clicked, the state will be updated according to the new data added to the view by the user.

Currently the inputs are bound to the store data, and so I have no reference to the "live" value of the inputs. When the user clicks save, how do I grab the "live" values?

Component Template

<input type="text" class="form-control" :value="item.name">
<input type="text" class="form-control" :value="item.price">
<button class="btn btn-primary" v-on:click="updateItem(item)">Save</button>

Component

data: function() {
  return {}
},
methods: {
  updateItem(item) {
    this.$store.commit('updateItem', item);
  },
},
computed: {
  items() {
    return this.$store.getters.getItem;
  }
}

Potential Solutions

I thought I could perhaps create a "clone" of the store, and bind the inputs to the cloned item data. Then this object will be updated as the view changes, and so I can grab those "live" values, and commit the data from the view to the store. Is this a good solution?

1
have a look at the docs: vuex.vuejs.org/en/forms.html, specifically the second paragraph "Two-way Computed Property". - sandrooco

1 Answers

2
votes

If you wanted to update without the user having to click the button, then I would suggest one of the methods explained in the docs.

But since you want to do it wen they click the button, try something like this:

<template>
    <form>
        <input type="text" class="form-control" v-model="item.name">
        <input type="text" class="form-control" v-model="item.price">

        <button class="btn btn-primary" @click.prevent="updateItem">Save</button>
    </form>
</template>

<script>
export default {
    data() {
        return {
            item: {
                name: null,
                price: null,
            }
        }
    },

    mounted() {
        // Set the default value of this.item based on what's in the store
        this.item = this.$store.getters.getItem
    },

    methods: {
        updateItem() {
            this.$store.commit('updateItem', this.item);
        }
    }
}
</script>