A
A
arctic072020-09-20 15:32:34
Vue.js
arctic07, 2020-09-20 15:32:34

How to correctly add an object to the store?

There is a form, 3 text fields. The task is to add information from them to the object, and add this object to the array that lies in the store.
How do I do add:
submit on the form. The object is assembled into a vehicle object from the v-model fields.

<form @submit.prevent="submit">
        <input
          type="text"
          placeholder="Name"
          v-model="vehicle.name"
        />
        <input
          type="text"
          placeholder="Description"
          v-model="vehicle.description"
        />
          <input
            id="rentInput"
            type="text"
            placeholder="Rent price"
            v-model="vehicle.rent"
          />
        </div>
        <button type="submit" :class="$style.modalSubmit">Complete</button>
      </form>


data: () => ({
    vehicle: {
      name: '',
      description: '',
      rent: '',
      type: 'custom'
    }
  }),


methods: {
    submit() {
      this.$store.commit("vehicles/addVehicle", this.vehicle);
    },
}


@store/vehicles.js
export const state = () => ({
  vehicles: [],
});

export const mutations = {
addVehicle(state, payload) {
    let vehicles = state.vehicles.concat(payload);
    state.vehicles = vehicles;
  },
};

Adding 1 object is fine, but when you start entering characters into the input to add the 2nd, an error pops up:

Error: [vuex] do not mutate vuex store state outside mutation handlers.

I found a solution to this problem in the documentation: https://vuex.vuejs.org/guide/forms.html
but I can't figure out how to apply the examples they give to my code... ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-09-20
@arctic07

Error: [vuex] do not mutate vuex store state outside mutation handlers.

Well, yes, as it should be. You place in the array located in the storage a reference to the object that you are working with in the component with the form.
Make a copy:
this.$store.commit('vehicles/addVehicle', { ...this.vehicle });
// или
addVehicle: (state, payload) => state.vehicles.push({ ...payload }),

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question