Answer the question
In order to leave comments, you need to log in
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,
};
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();
},
<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>
Answer the question
In order to leave comments, you need to log in
Object.assign does not copy deep nesting, and two-way binding changes state.
Use cloneDeep
computed: {
...mapGetters('form', 'getFormFromStore'),
form: {
get () {
return this.getFormFromStore;
},
set (value) {
this.setForm(value);
}
}
},
methods: {
...mapActions('form', 'getForm'),
...mapMutations('form', 'setForm'),
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question