商品未显示在pinia state in vue3的购物车中

c8ib6hqw  于 2023-01-14  发布在  Vue.js
关注(0)|答案(1)|浏览(113)

我的购物车项目是不显示在这车(这是在状态使用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

<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

<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>

为什么对我不起作用?我想我做的每件事都对...

avwztpqn

avwztpqn1#

shop.vue只是将id号压入存储的cart数组

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

cart.vue正在尝试显示cart数组,就好像它包含完整的产品对象,而不仅仅是ID

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

通过更改shop.vue以添加完整的item(而不是仅添加item.id),可以轻松修复此问题

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

相关问题