If you need to add only one item in this array
, it is necessary to do as in the above mode overwriting everything?
It depends on how your status update is being sent, if you are sending all the items from array
need to save all and if sending only the new position then a push
:
state.array.push(item);
or as it is seen and done by many so:
state.array = [...state.array, item]; // ou state.array = newItems;
adds or changes all items.
The two forms are correct does not have in this aspect comparison of performance and in my opinion the second is actually the copy of the new value with all items. In the case of Vue
that works (push
or full copy) in others such as React
only give a push
does not resolve need to copy the new array
and send, then, the second form is more compatible and usual by most, not think it is fashionable but, yes, the correct way to change the state.
A functional example:
const store = new Vuex.Store({
state: {
items: []
},
mutations: {
addItem(state, value) {
state.items = [...state.items, value]; // correto
//state.items.push(value); // também correto
}
},
actions: {
addItem(context, value) {
context.commit("addItem", value);
}
}
});
var vm = new Vue({
el: '#app',
store,
data: {
value: ''
},
computed: {
items() {
return this.$store.state.items;
}
},
methods: {
handleAddItem: function() {
if (this.value) {
this.$store.dispatch("addItem", this.value);
} else {
alert("Digite o item!");
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.2/vuex.min.js"></script>
<div id="app">
<div>
<p>
<input type="text" v-model="value" />
<button v-on:click="handleAddItem">Add Item</button>
</p>
<ul>
<li v-for="(item,index) in items" v-bind:key="index">{{item}}</li>
</ul>
</div>
</div>
References
Excellent Reply Man! Thank you very much! So I believe it is possible to use push/unshift normally in state and still maintain reactivity.
– Rubens Barbosa
In the case of
Vue
I believe it does, but as there is no pattern in theReact
for example can’t! @Rubensbarbosa.– novic