簡體   English   中英

如何從另一個突變 Vuex 中捕獲突變的返回值

[英]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)); }, }

likedCardsHandler是動作還是突變?
如果它是一個動作,您可以在動作上下文中找到它並從那里使用它。

有了這樣的東西

actions: {
  likedCardsHandler ({ getters }) {
    console.log('here', getters.isCardLiked)
  }
}

否則,我想你可以試試const card = isCardLiked

this不是在商店本身中定義的,因為它是一個.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)); } }, }

特別感謝@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM