I am trying to bind my form’s fields with my vuex store in Nuxt JS. It works fine with normal text fields with get()
set()
in computed
. But having trouble in customizing getting and setting manually. I am trying to push objects to an array in a specific format from my template to store and also keep the binding among them. Here is my code:
JavaScript
x
69
69
1
<template>
2
<div class="container setting-form-area-business">
3
<b-form-group v-for="(input, index) in phoneNumbers" :key="`phoneInput-${index}`">
4
<label>Mobile Number {{index+1}}*</label>
5
<b-input-group>
6
<b-form-input v-model="input.phone" @input="updateStore" class="custom-form-input-business">
7
</b-form-input>
8
<b-input-group-append v-show="phoneNumbers.length > 1">
9
<b-button class="mobile-number-remove-btn" @click="removeField(index, phoneNumbers)"></b-button>
10
</b-input-group-append>
11
12
</b-input-group>
13
14
</b-form-group>
15
16
<b-form-group>
17
18
<b-button class="jh-btn2" @click="addField">Add More Mobile Number</b-button>
19
20
</b-form-group>
21
22
</div>
23
</template>
24
<script>
25
export default {
26
props: [
27
'visited'
28
],
29
30
data() {
31
return {
32
phoneNumbers: this.$store.state.business.formvalue.mobileNumber.length ? this.$store.state.business.formvalue
33
.mobileNumber : [{
34
phone: ""
35
}],
36
37
38
}
39
},
40
computed: {
41
mobilenumbers() {
42
return this.$store.state.business.formvalue.mobileNumber
43
},
44
45
},
46
methods: {
47
48
addField() {
49
this.phoneNumbers.push({
50
value: ""
51
});
52
53
},
54
removeField(index, fieldType) {
55
56
fieldType.splice(index, 1);
57
console.log('fieldType', fieldType);
58
this.emitErrorStatus();
59
},
60
updateStore() {
61
this.$store.commit('business/setformmobileNumber', {
62
mobileNumber: this.phoneNumbers
63
})
64
}
65
},
66
}
67
68
</script>
69
this was working fine when I was in vue, but coming to nuxt, it is giving me error
[vuex] do not mutate vuex store state outside mutation handlers.
Advertisement
Answer
As told by the error, you should not mutate the state. There are several ways to handle this one. A quick search here could give you a lot of answers.
This is mine (using Lodash’s cloneDeep
): https://stackoverflow.com/a/66262659/8816585