0

我正在使用 Vue 3、Vuex 4 和 TypeScript。我有以下型号:

class CartItem {
  id: number;

  name: string;

  price: number;

  quantity: number;

  // other stuff...
}

class Cart {
  items: CartItem[];

  // other stuff...
}

我的 Vuex 商店有以下状态模式:

type State = {cart: Cart};

我有一个Cart组件,我在其中迭代cart.items并呈现 CartItem 组件,如下所示:

<cart-item v-for="item in cart.items" :key="item.id" />

现在,在CartItem组件中,我需要访问返回的单个的计算获取器。我可以在 CartItem.vue 文件中定义一个计算属性,但这不能重用。这是我需要的许多计算/获取器之一。totalPriceCartItemquantity * price

起初我尝试将 TypeScript getter 添加到我的CartItem模型中,如下所示:

  get totalPrice(): number{
    return this.quantity * this.price;
  }

但是当我这样做时它没有返回任何值:

<span>
{{item.totalPrice}}
</span>

它是未定义的。我试图将它从 getter 更改为方法。我尝试从组件中的计算属性调用它。还没有运气!

似乎我应该使用 Vuex getter,但问题是,我怎样才能获得每个CartItems 的 totalPrice?

4

0 回答 0