Reputation: 21
I'm a beginner studying Vue Js. I'm trying to add an item to a list but it doesn't work. My list is in the state of the store, and the function to add a new element is in the mutations. Please is the function that allows to add a new element badly coded or the error is elsewhere.
Please help me.
There is my Vuex store code
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
produits: [
{text: "ananas", checked: true},
{text: "banane", checked: false},
{text: "orange", checked: true},
],
newProduit: ''
},
mutations: {
addItem: function(ecrit) {
ecrit= this.state.newProduit.trim();
if(ecrit) {
this.state.produits.push({
text:ecrit,
checked: false
});
}
}
},
actions: {},
modules: {},
});
There is my component code
<template>
<div>
<b-input-group class="mt-3">
<b-form-input></b-form-input>
<b-input-group-append>
<b-button variant="info" v-on:click="ajoutElement">Ajouter</b-button>
</b-input-group-append>
</b-input-group>
</div>
</template>
<script>
export default {
computed: {
ajoutElement: {
get() {
return this.$store.state.produits;
},
set(value) {
this.$store.commit('addItem',value)
}
}
}
}
</script>
Thanks in advance for your help
Upvotes: 2
Views: 1447
Reputation: 3036
You should add action for each of the action that you are making from component.
I have added an action addItemAction. You can see this for reference, Ideally you should have action-> commits-> mutation
In a large application, you can even create separate modules should have function for each of modules to perform action-> commits-> mutation
component
set(value) {
this.$store.dispatch('addItemAction',value); // Dispatch action with name and params.
}
Update vuex store now
export default new Vuex.Store({
state: {
produits: [
{text: "ananas", checked: true},
{text: "banane", checked: false},
{text: "orange", checked: true},
],
newProduit: ''
},
mutations: {
addItem: function(ecrit) {
ecrit= this.state.newProduit.trim();
if(ecrit) {
this.state.produits.push({
text:ecrit,
checked: false
});
}
}
},
actions: {
addItemAction: function(context, ecrit){
context.commit('addItem', ecrit); // Commit from here.
}
},
modules: {},
});
Upvotes: 2