简体   繁体   English

vue3 中 pinia state 中的购物车中未显示的项目

[英]items not showing in cart in pinia state in vue3

my cart items is not showing in the cart(which is in state using pinia) after adding them using an action from a button in the shop page使用商店页面中按钮的操作添加它们后,我的购物车商品未显示在购物车中(使用 pinia 在 state 中)

my code:我的代码:

store.js(using pinia) store.js(使用 pinia)

import { defineStore } from "pinia";
import Products from "../db.json";

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

shop.vue商店.vue

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

const storeCounter = useCounterStore()

</script>

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 }}</div>
    </div>
</template>

<script setup>
import { useCounterStore } from '../stores/counter';
import Products from "../db.json"

const storeCounter = useCounterStore()

</script>

why it is not working for me?为什么它不适合我? i assume i did everything right...我想我做的一切都是对的...

shop.vue is only pushing the id number into the store's cart array shop.vue只是将 id 号推入商店的cart数组

<button @click="storeCounter.addToCart(item.id)">

cart.vue is attempting to display the cart array as if contains full product objects and not just the ids cart.vue试图显示cart数组,就好像包含完整的产品对象而不仅仅是 id

<div class="cartitems" v-for="item in storeCounter.cart" :key="item.id">
  {{ item.name }} {{ item.price }}
</div>

This can be easily fixed by changing shop.vue to add the full item instead of just item.id这可以通过更改shop.vue以添加完整item而不只是item.id来轻松解决

<button @click="storeCounter.addToCart(item)">

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

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