我正在使用 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 文件中定义一个计算属性,但这不能重用。这是我需要的许多计算/获取器之一。totalPrice
CartItem
quantity * price
起初我尝试将 TypeScript getter 添加到我的CartItem
模型中,如下所示:
get totalPrice(): number{
return this.quantity * this.price;
}
但是当我这样做时它没有返回任何值:
<span>
{{item.totalPrice}}
</span>
它是未定义的。我试图将它从 getter 更改为方法。我尝试从组件中的计算属性调用它。还没有运气!
似乎我应该使用 Vuex getter,但问题是,我怎样才能获得每个CartItem
s 的 totalPrice?