How to fix the error of unknown mutation type in Vuex?
Answer a question I have googled this error however the answers I get, didn't help me. I am trying to make a like-dislike count with using Vuex. I am using jsonplaceholder for data. Here I take my dat
Answer a question
I have googled this error however the answers I get, didn't help me. I am trying to make a like-dislike count with using Vuex. I am using jsonplaceholder for data. Here I take my data and setting a like attribute for all the objects.
actions: {
async fetchPhotos({commit}) {
const response = await axios.get('https://jsonplaceholder.typicode.com/photos');
commit('setPhotos', response.data.splice(0,100))
},
}
mutations: {
setPhotos: (state, photos) => {
(state.albumList = photos);
state.albumList.forEach(element => element.likes = 0)}
}
After in my dom I want to use one button for dislike and other for like. I want to display the like counter when I click the buttons.
<div v-for="photos in allPhotos" :key="photos.id">
<div class="card" @click="detail(photos)"><img :src="photos.thumbnailUrl" alt=""></div>
<div class="likes">
<div class="myButton" ><button class="red" @click="minus(photos.id)"><i class="fas fa-minus"></i></button></div>
<div>{{photos.likes}}</div>
<div class="myButton "><button class="green" @click="plus(photos.id)"><i class="fas fa-plus"></i></button></div>
</div>
</div>
So I added minus mutations in my store and in my script.
methods: {
...mapMutations(['minus']),
state: {
albumList : [],
},
mutations: {
minus: (state, id) => {
state.albumList[id-1].likes--
},
After all this, I am having an error:
[vuex] unknown mutation type: minus.
I can't see what I am doing wrong here.
PS:I also trimmed the code for it to be clearer.
Answers
Here is the working example. Also double check your vuex store configuration/registration.
const store = new Vuex.Store({
state: {
items: [
{
title: "item1",
likes: 10
},
{
title: "item2",
likes: 24
}
]
},
actions: {
like({ commit }, id) {
commit("LIKE_ITEM", id);
},
dislike({ commit }, id) {
commit("DISLIKE_ITEM", id);
}
},
mutations: {
LIKE_ITEM(state, id) {
state.items[id].likes++;
},
DISLIKE_ITEM(state, id) {
state.items[id].likes--;
}
},
getters: {
items(state) {
return state.items;
}
}
});
new Vue({
el: "#app",
store,
computed: {
items() {
return this.$store.getters.items;
}
},
data: () => {
return {};
},
methods: {
like(id) {
this.$store.dispatch("like", id);
},
dislike(id) {
this.$store.dispatch("dislike", id);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.5.1/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
<div v-for='(item, i) in items' :key="i">
{{item.title }}: {{item.likes}} likes
<button @click='like(i)'>Like +</button> <button @click='dislike(i)'>Dislike -</button>
</div>
</div>
更多推荐
所有评论(0)