简体   繁体   English

无法使用 pinia 从 vue 3 中的购物车中删除商品

[英]cannot remove items from cart in vue 3 with pinia

so in the console log it is saying it is being removed from the cart but i can still see the items in the cart... how can i remove them from the cart?所以在控制台日志中它说它正在从购物车中删除,但我仍然可以看到购物车中的项目...我如何从购物车中删除它们? im using pinia for state management and the cart is in the state. why it is not working for me?我正在使用 pinia 进行 state 管理,购物车在 state 中。为什么它对我不起作用?

the code:代码:

shop.vue商店.vue

<template>
  <div class="shop">
    Cart Items: <cart-badge :count="cartLength">{{ count }}</cart-badge>
    <h1>shop</h1>
    <div class="products" v-for="item in Products" :key="item.id">
      {{ item.name }} {{ item.price }}$
      <button @click="storeCounter.addToCart(item)">Add to Cart</button>
    </div>
  </div>
</template>
<script setup>
import { useCounterStore } from "../stores/counter";
import Products from "../db.json";
import CartBadge from "../components/CartBadge.vue";
import { computed } from "vue";

const storeCounter = useCounterStore();

const cartLength = computed(() => {
  return storeCounter.cart.length;
});
</script>

store.js(pinia) store.js(pinia)

import { defineStore } from "pinia";

export const useCounterStore = defineStore("counter", {
  state: () => ({
    cart: [],
  }),
  actions: {
    addToCart(id) {
      this.cart.push(id);
      console.log("test passed!");
    },
    removeFromCart(id) {
      this.cart.splice(id);
      console.log("removed from cart!");
    },
  },
});

cart.vue购物车.vue

<template>
    <div class="cart">
        <h1>cart</h1>
        <div class="cartitems" v-for="item in storeCounter.cart" :key="item.id">{{ item.name }} {{ item.price }}$
        <button @click="storeCounter.removeFromCart(item.id)">X</button>
        </div>
    </div>
</template>

<script setup>
import { useCounterStore } from '../stores/counter';

const storeCounter = useCounterStore()

</script>

Splice uses the index of the item to delete it. Splice 使用项目的索引来删除它。

Do this instead;改为这样做;

removeFromCart(id) {
    let cartItemIndex = this.cart.findIndex(x => x.id === id);

    if (cartItemIndex >= 0) {
        this.cart.splice(cartItemIndex, 1);
        console.log("Removed from cart");
    }
}

or if you don't want to use splice anymore (and if performance matters);或者如果您不想再使用拼接(如果性能很重要);

removeFromCart(id) {
    this.cart = this.cart.filter(x => x.id !== id);
    console.log("Removed from cart");
}

Please use more descriptive parameter names.请使用更具描述性的参数名称。 Rename " id " to " item " in addToCart , since you're not just adding the item id, but the entire item.addToCart中将“ id ”重命名为“ item ”,因为您不仅要添加商品 ID,还要添加整个商品。 This can be confusing to other developers and make your code unreadable.这可能会让其他开发人员感到困惑,并使您的代码难以阅读。

addToCart(item) {
    this.cart.push(item)
    console.log('test passed!')
}

References: splice filter参考资料: 拼接滤波器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM