状态对Vuex无反应

时间:2020-11-09 07:46:35

标签: javascript vue.js vuex

当我单击时,我试图在Vuex中减少​​或增加购物车,但是直到重新渲染组件或再次在Vue的devtools中单击“提交”,更改才会反映出来。

我的商店的样子:

  • 状态
state: {
  toggleSideBar: false,
  cart: [],
},
  • 动作
action:{
  incrementCart: ({ commit }, payload) => {
  commit("INCREMENT_CART", payload);
},
 addToCart: ({ commit, state }, payload) => {
      commit("ADD_TO_CART", payload);
    },
}
  • 变异
mutation:{
INCREMENT_CART(state, payload) {
  let index = state.cart.findIndex((x) => x.id === payload);
  state.cart[index].amount += 1;
},
  ADD_TO_CART(state, payload) {
      let amount = 1;
      if (state.cart.length === 0) {
        payload.amount = amount;
        return state.cart.push(payload);
      } else {
        if (state.cart.some((cart) => cart.id === payload.id)) {
          let index = state.cart.findIndex((x) => x.id === payload.id);
          state.cart[index].amount += amount;
        } else {
          payload.amount = amount;
          state.cart.push(payload);
        }
      }
    },
}

  • 然后在我的组件中
computed: {
  cartData() {
    return this.$store.state.cart;
    console.log(this.$store.state.cart);
  },
}

然后将值作为道具传递到各个购物车

1 个答案:

答案 0 :(得分:0)

您需要像这样在Vuex中创建一个吸气剂:

getters: {
    getCart(state) {
        return state.cart;
    }
}

然后在您的计算中,您需要像这样调用您的getter:

import { mapGetters } from 'vuex';

export default {
    
    computed: {
        ...mapGetters(['getCart']);
    }
}

最后在html标记中,您需要这样调用getter:

<div v-for="item in getCart">item.quantity</div>