Vue3组合式API与Pinia状态管理实战:构建可复用的电商购物车组件
引言
Vue3的组合式API(Composition API)为组件逻辑复用提供了更灵活的方式,结合Pinia状态管理库,可以构建出高性能、可维护的电商购物车组件。本文将详细介绍如何使用Vue3和Pinia创建一个可复用的购物车组件,涵盖状态管理、组件通信和功能实现等关键环节。
正文
1. 环境准备与项目初始化
首先确保已安装Vue3和Pinia。在项目中创建购物车相关文件结构:
- stores/cart.ts – Pinia购物车状态管理
- components/Cart.vue – 购物车主组件
- components/CartItem.vue – 购物车项组件
2. 使用Pinia管理购物车状态
创建cart store,定义购物车状态和方法:
import { defineStore } from \'pinia\'
export const useCartStore = defineStore(\'cart\', {
state: () => ({
items: [] as Array
}),
getters: {
total: (state) => state.items.reduce((sum, item) => sum + item.price * item.quantity, 0),
itemCount: (state) => state.items.reduce((sum, item) => sum + item.quantity, 0)
},
actions: {
addItem(product: { id: number; name: string; price: number }) {
const existingItem = this.items.find(item => item.id === product.id)
if (existingItem) {
existingItem.quantity++
} else {
this.items.push({ ...product, quantity: 1 })
}
},
removeItem(id: number) {
const index = this.items.findIndex(item => item.id === id)
if (index > -1) {
if (this.items[index].quantity > 1) {
this.items[index].quantity--
} else {
this.items.splice(index, 1)
}
}
},
clearCart() {
this.items = []
}
}
})
3. 构建可复用的购物车组件
主组件Cart.vue使用组合式API整合购物车功能:
<template>
<div class=\"cart\">
<h2>购物车</h2>
<div v-if=\"cartStore.items.length === 0\">购物车为空</div>
<div v-else>
<cart-item
v-for=\"item in cartStore.items\"
:key=\"item.id\"
:item=\"item\"
/>
<div class=\"cart-summary\">
<p>总计: ¥{{ cartStore.total.toFixed(2) }}</p>
<button @click=\"cartStore.clearCart\">清空购物车</button>
</div>
</div>
</div>
</template>
<script setup lang=\"ts\">
import { useCartStore } from \'@/stores/cart\'
import CartItem from \'./CartItem.vue\'
const cartStore = useCartStore()
</script>
4. 实现购物车项组件
CartItem.vue负责展示单个商品项并处理数量调整:
<template>
<div class=\"cart-item\">
<span>{{ item.name }} - ¥{{ item.price }}</span>
<div class=\"quantity-controls\">
<button @click=\"decreaseQuantity\">-</button>
<span>{{ item.quantity }}</span>
<button @click=\"increaseQuantity\">+</button>
</div>
</div>
</template>
<script setup lang=\"ts\">
import { useCartStore } from \'@/stores/cart\'
const props = defineProps({
item: {
type: Object,
required: true
}
})
const cartStore = useCartStore()
const increaseQuantity = () => {
cartStore.addItem(props.item)
}
const decreaseQuantity = () => {
cartStore.removeItem(props.item.id)
}
</script>
5. 组件复用与扩展
通过组合式API和Pinia,购物车组件可以轻松复用:
- 在商品详情页添加\”加入购物车\”按钮,调用cartStore.addItem
- 在导航栏显示购物车商品数量:{{ cartStore.itemCount }}
- 通过provide/inject将cartStore注入子组件,避免层层传递
总结
通过Vue3组合式API和Pinia的配合,我们构建了一个功能完整、可复用的购物车组件。这种架构具有以下优势:
- 逻辑集中管理:所有购物车状态和方法都在Pinia store中统一处理
- 组件高度解耦:购物车组件可以独立于业务逻辑使用
- 易于扩展:通过组合式API可以轻松添加新功能如优惠券、运费计算等
- 性能优化:Pinia的响应式系统确保状态更新高效
这种实现方式不仅适用于电商购物车,也可以推广到其他需要状态管理的复杂组件场景,为构建大型Vue3应用提供了可靠的模式参考。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...
