东莞高端品牌网站建设,茂名网站制作,手机端网页制作,网站建设 开办费欢迎来到编程星辰海的博客讲解 看完可以给一个免费的三连吗#xff0c;谢谢大佬#xff01; 目录
一、Pinia 深度解析
1. Pinia 核心设计
2. 核心概念图解
3. Store 类型对比
Option Store#xff08;选项式#xff09;
Setup Store#xff08;组合式#xff09;
…欢迎来到编程星辰海的博客讲解 看完可以给一个免费的三连吗谢谢大佬 目录
一、Pinia 深度解析
1. Pinia 核心设计
2. 核心概念图解
3. Store 类型对比
Option Store选项式
Setup Store组合式
4. 响应式原理
二、购物车状态管理实战
1. 项目结构
2. 核心 Store 实现stores/cart.js
3. 商品列表组件ProductList.vue
4. 购物车组件ShoppingCart.vue
三、实现效果说明
四、学习要点总结
五、扩展阅读推荐
官方资源
优质文章
进阶教程 一、Pinia 深度解析
1. Pinia 核心设计
Pinia 是 Vue 官方推荐的新一代状态管理库具有以下核心优势
TypeScript 原生支持完整的类型推断和自动补全模块化架构天然支持代码分割和按需加载轻量无冗余相比 Vuex 减少 40% 的代码量组合式 API完美对接 Vue3 的组合式编程范式Devtools 整合完整的时间旅行调试支持
2. 核心概念图解 3. Store 类型对比
Option Store选项式
JAVASCRIPT export const useCounterStore defineStore(counter, {state: () ({ count: 0 }),getters: {double: (state) state.count * 2,},actions: {increment() {this.count},},
})Setup Store组合式
JAVASCRIPT export const useCounterStore defineStore(counter, () {const count ref(0)const double computed(() count.value * 2)function increment() {count.value}return { count, double, increment }
})4. 响应式原理
Pinia 基于 Vue3 的 reactive() 实现响应式系统
State 自动转换为 reactive 对象Getters 使用 computed 实现计算缓存Actions 作为状态操作方法
二、购物车状态管理实战
1. 项目结构
TEXT /src├── stores│ └── cart.js├── components│ ├── ProductList.vue│ └── ShoppingCart.vue└── App.vue2. 核心 Store 实现stores/cart.js
JAVASCRIPT import { defineStore } from pinia
import { computed, ref } from vueexport const useCartStore defineStore(cart, () {// 状态定义const items ref([]) // 购物车商品数组const taxRate 0.1 // 税率常量// Getter带参数的派生状态const cartTotal computed(() items.value.reduce((sum, item) sum item.price * item.quantity, 0))const totalWithTax computed(() cartTotal.value * (1 taxRate))// Action添加商品幂等操作const addToCart (product, quantity 1) {const existing items.value.find(item item.id product.id)if (existing) {// 商品存在时增加数量existing.quantity quantity} else {// 新商品添加购物车items.value.push({...product,quantity,addedAt: new Date().toISOString()})}}// Action移除商品支持完全移除和减少数量const removeFromCart (productId, quantity 1) {const index items.value.findIndex(item item.id productId)if (index -1) returnif (items.value[index].quantity quantity) {// 完全移除商品items.value.splice(index, 1)} else {// 减少商品数量items.value[index].quantity - quantity}}// Action清空购物车const clearCart () {items.value []}return {items,cartTotal,totalWithTax,addToCart,removeFromCart,clearCart}
})3. 商品列表组件ProductList.vue
VUE script setup
import { useCartStore } from /stores/cartconst cartStore useCartStore()
const products [{ id: 1, name: Vue T-Shirt, price: 29.99 },{ id: 2, name: Pinia Mug, price: 15.50 },{ id: 3, name: Vuex Book, price: 39.99 }
]
/scripttemplatediv classproduct-listh2Available Products/h2div v-forproduct in products :keyproduct.id classproduct-itemh3{{ product.name }}/h3pPrice: \${{ product.price.toFixed(2) }}/pbutton clickcartStore.addToCart(product)Add to Cart/button/div/div
/template4. 购物车组件ShoppingCart.vue
VUE script setup
import { useCartStore } from /stores/cart
import { storeToRefs } from piniaconst cartStore useCartStore()
const { items, cartTotal, totalWithTax } storeToRefs(cartStore)
/scripttemplatediv classshopping-carth2Shopping Cart/h2div v-ifitems.length 0 classempty-cartYour cart is empty/divdiv v-elsediv v-foritem in items :keyitem.id classcart-itemh3{{ item.name }}/h3pQuantity: {{ item.quantity }}button clickcartStore.removeFromCart(item.id, 1)-/buttonbutton clickcartStore.addToCart(item)/button/ppPrice: \${{ (item.price * item.quantity).toFixed(2) }}/pbutton clickcartStore.removeFromCart(item.id, item.quantity)Remove/button/divdiv classtotalspSubtotal: \${{ cartTotal.toFixed(2) }}/ppTax (10%): \${{ (totalWithTax - cartTotal).toFixed(2) }}/pp classtotalTotal: \${{ totalWithTax.toFixed(2) }}/p/divbutton clickcartStore.clearCart classclear-btnClear Cart/button/div/div
/template三、实现效果说明 图示说明用户添加商品、调整数量、删除商品时各组件自动同步状态
状态共享多组件同时访问同一购物车状态响应式更新价格计算实时同步操作隔离商品增减逻辑集中管理类型安全完整的TS类型推断
四、学习要点总结 核心概念 Store 作为状态容器State 定义应用状态Getters 实现派生数据Actions 封装业务逻辑 最佳实践 JAVASCRIPT // 正确的状态解构方式
const { count } storeToRefs(store)
// 错误的方式破坏响应式
const { count } store架构原则 单一职责每个Store聚焦特定领域低耦合组件不直接操作其他Store高内聚相关逻辑集中管理 调试技巧 JAVASCRIPT // 浏览器控制台访问
const store useCartStore()
store.$patch({...})
store.$subscribe((mutation) {console.log(状态变更:, mutation)
})五、扩展阅读推荐
官方资源
Pinia 官方文档Vue 状态管理指南Pinia 与 Vuex 对比指南
优质文章
深入理解 Pinia 架构设计企业级 Pinia 最佳实践Pinia 插件开发指南SSR 场景下的 Pinia 使用Pinia 单元测试全攻略
进阶教程
JAVASCRIPT // 持久化插件示例
import { createPinia } from pinia
import { createPersistedState } from pinia-plugin-persistedstateconst pinia createPinia()
pinia.use(createPersistedState({auto: true, // 自动持久化所有Storestorage: sessionStorage
}))建议运行示例并通过 Vue Devtools 观察状态变更过程加深理解。义和测试用例。