[英]How to catch returned value from mutation in another mutation Vuex
我正在嘗試從一個操作中訪問一個 getter,但它給出了一個錯誤: getters.isCardLiked is not a function
商店/index.js
export const getters = { isCardLiked(state, id) { const found = state.likedCards.find(likedCard => likedCard.id === id) console.log('found', found); // object return found }, }, export const actions = { likedCardsHandler({ dispatch, commit, getters }, id) { console.log('here', getters.isCardLiked(id)); }, }
export const getters = { isCardLiked: (state) => (id) => { const found = state.likedCards.find(likedCard => likedCard.id === id) console.log('found', found); // object return found }, } export const actions = { likedCardsHandler({ dispatch, commit, getters }, id) { console.log('here', getters.isCardLiked(id)); } }, }
特別感謝@kissu
您可以使用帶有過濾器的計算方法來返回這樣找到的對象。 所以我猜有一個像這樣的按鈕。 商店頁面
import createStore from 'vuex';
const store=createStore({
state:{
cards:{
A:{
id:1.
likes:0
},
B:{
id:2,
likes:0
}
}
}
actions:{
changeCards({commit}, payload){
commit('changeCard',payload)
}
}
mutations:{
changeCard(state,payload){
if(state.cards.id==payload)
state.cards.likes++;
}
}
})
export default store;
現在在 App.js 中
<ul>
<li v-for="card in cards">
<button @click="likeButtonClicked(card.id)">Like</button>
</li>
</ul>
<li v-for="likedCard in likedCards">{{likedCard}}
</li>
<ul>
<li></li>
</ul>
methods:{
likeButtonClicked(id){
this.$store.dispatch('changeCards',id);
}
}
computed:{
cards(){
return this.$store.state.cards;
}
likedCards(){
return cards.filter(card=>card.id.includes(this.$store.state.cards.likes>0))
}
我希望你明白這一切的意義。 我希望這有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.