T
T
tryToFrontEnd2021-11-30 15:41:55
Vue.js
tryToFrontEnd, 2021-11-30 15:41:55

Bind form from vuex?

I'm just trying out vue and I have a question.
Let's say I have a large form that is stored in vuex.

How can I bind it to the form in the component so that there is no error "you cannot change the state outside the mutation"

example store

const action = {
  async getForm({ commit }, id) {
    try {
      const response = await axios.get(`url/${id}`);
      commit('setForm', response.data);
    } catch(e) {
      console.error(e);
    }
  },
};

const mutations = {
  setForm(state, payload) {
    state.form = payload;
  },
};

const getters = {
  getFormFromStore = state => state.form,
};


This is how the code in the component looks like
data() {
  return {
    form: {},
  };
},
computed: {
  ...mapGetters('form', 'getFormFromStore'),
},
methods: {
  ...mapActions('form', 'getForm'),
},
watch: {
  getFormFromStore: {
    deep: true,
    handler(newVal) {
      this.form = Object.assign({}, newVal);
    },
  },
},
async mounted() {
  await this.getForm();
},


Well, the form
<div>
  <v-form>
    <v-text-field v-model=form.name/>
    <v-text-field v-model=form.lastName/>
    <v-text-field v-model=form.age/>
    <v-text-field v-model=form.address.street/>
    <v-text-field v-model=form.address.house/>
    <v-text-field v-model=form.children.girl/>
    <v-text-field v-model=form.children.girl.name/>
  </v-form>
</div>


When I try to change the value, I get an error. Tell me please

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sashqa, 2021-11-30
@tryToFrontEnd

Object.assign does not copy deep nesting, and two-way binding changes state.
Use cloneDeep

D
Dima Pautov, 2021-11-30
@bootd

computed: {
  ...mapGetters('form', 'getFormFromStore'),
  form: {
    get () {
      return this.getFormFromStore;
    },
    set (value) {
      this.setForm(value);
    }
  }
},
methods: {
  ...mapActions('form', 'getForm'),
  ...mapMutations('form', 'setForm'),
},

data delete and watch too

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question