Vue3——第 22 篇:Pinia——新一代状态管理(上)

本篇定位:Pinia 是 Vue 官方新一代的状态管理库,它轻量、直观、类型安全,是 Vuex 的完美继任者。本篇将系统讲解 Pinia 的核心概念------Store、State、Getters 和 Actions,并深入探讨三种 Store 定义方式的使用场景。读完本篇,你将能够熟练使用 Pinia 管理 Vue 应用的全局状态。


一、为什么需要状态管理?

1.1 组件间状态共享的挑战

在 Vue 应用中,组件之间经常需要共享状态:

复制代码
App.vue
├── Header.vue         ← 需要用户信息
├── Sidebar.vue        ← 需要用户权限
│   └── Menu.vue       ← 需要用户权限
└── Dashboard.vue      ← 需要用户信息
    └── UserProfile.vue ← 需要用户信息

不使用状态管理时的问题:

方案 问题
Props 传递 深层嵌套时产生 Props 钻探,中间组件被迫接收无关数据
事件传递 子组件向多层父组件传递事件,代码冗长
Provide/Inject 缺乏响应式类型安全,依赖关系不明确
全局对象 无法追踪变化,难以调试

1.2 Pinia 的定位

Pinia 是 Vue 官方团队 开发的状态管理库,最初是 Vuex 5 的实验性实现,后来独立发展。

Pinia 名字的含义:Pinia 在西班牙语中意为"菠萝"(piña),取这个名字是因为菠萝由多个小花聚合而成(如同 Store 聚合了多个模块),且名字听起来很美味 🍍。

1.3 Pinia vs Vuex 4

维度 Pinia Vuex 4
Mutations ❌ 无(直接用 Actions 修改) ✅ 需要定义 Mutations
TypeScript 支持 原生完美支持 需要额外类型定义
Store 定义 简洁,支持 Options / Setup 两种风格 需要定义 State、Getters、Mutations、Actions
模块管理 Store 天然是模块化的 需要手动命名空间
代码体积 更小(~1KB) 更大
DevTools ✅ Vue DevTools 完美集成 ✅ 支持
学习曲线 平缓 陡峭
状态更新 直接修改 必须通过 Mutation 或 Action
服务器端渲染 原生支持 需要额外配置

Pinia 的核心优势总结:

复制代码
1. 没有 Mutations ------ 更少的样板代码
2. 完美的 TypeScript 支持 ------ 自动类型推导
3. 扁平化结构 ------ 没有嵌套模块,Store 天然独立
4. 轻量级 ------ 核心库极小
5. 官方 DevTools 支持 ------ Vue 生态无缝集成

二、安装与配置

2.1 安装 Pinia

bash 复制代码
# 使用 npm
npm install pinia

# 使用 pnpm(推荐)
pnpm add pinia

2.2 创建 Pinia 实例

typescript 复制代码
// src/stores/index.ts
import { createPinia } from 'pinia'

// 创建 Pinia 实例
const pinia = createPinia()

export default pinia

2.3 在 Vue 应用中注册 Pinia

typescript 复制代码
// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import pinia from './stores'

const app = createApp(App)

app.use(pinia)  // 注册 Pinia 插件
app.mount('#app')

2.4 项目结构建议

复制代码
src/
├── stores/
│   ├── index.ts           # Pinia 实例配置
│   ├── user.ts            # 用户 Store
│   ├── app.ts             # 应用配置 Store
│   ├── cart.ts            # 购物车 Store
│   ├── product.ts         # 产品 Store
│   └── index.ts           # 统一导出
├── main.ts
└── App.vue

三、定义 Store

Pinia 提供了 三种方式 定义 Store:

方式 适用场景 特点
Options Store 大多数场景 类似 Vuex,结构清晰
Setup Store 复杂逻辑 类似 Composition API,更灵活
组合式 Store 逻辑复用 使用组合式函数构建

3.1 Options Store(推荐新手)

使用 defineStore 并传入一个包含 state、getters、actions 的选项对象:

typescript 复制代码
// stores/counter.ts
import { defineStore } from 'pinia'

// defineStore 返回一个函数,调用后创建 Store 实例
export const useCounterStore = defineStore('counter', {
  // 1. State:返回初始状态的函数
  state: () => ({
    count: 0,
    name: 'Counter'
  }),
  
  // 2. Getters:计算属性(类似 computed)
  getters: {
    doubleCount: (state) => state.count * 2,
    // 使用 this 访问其他 getters
    formattedCount: (state) => {
      return `当前计数:${state.count}`
    }
  },
  
  // 3. Actions:修改状态的方法(支持异步)
  actions: {
    increment() {
      this.count++
    },
    incrementBy(amount: number) {
      this.count += amount
    },
    async asyncIncrement() {
      await new Promise(resolve => setTimeout(resolve, 1000))
      this.count++
    },
    reset() {
      this.count = 0
    }
  }
})

3.2 Setup Store(推荐进阶)

使用 defineStore 并传入一个 函数,在函数中使用组合式 API:

typescript 复制代码
// stores/counter.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCounterStore = defineStore('counter', () => {
  // 1. State:使用 ref / reactive
  const count = ref(0)
  const name = ref('Counter')
  
  // 2. Getters:使用 computed
  const doubleCount = computed(() => count.value * 2)
  const formattedCount = computed(() => `当前计数:${count.value}`)
  
  // 3. Actions:普通函数
  function increment() {
    count.value++
  }
  
  function incrementBy(amount: number) {
    count.value += amount
  }
  
  async function asyncIncrement() {
    await new Promise(resolve => setTimeout(resolve, 1000))
    count.value++
  }
  
  function reset() {
    count.value = 0
  }
  
  // 返回需要暴露的内容
  return {
    // State
    count,
    name,
    // Getters
    doubleCount,
    formattedCount,
    // Actions
    increment,
    incrementBy,
    asyncIncrement,
    reset
  }
})

3.3 Options vs Setup 风格对比

维度 Options Store Setup Store
语法风格 类似 Vuex,对象配置 类似 Composition API
类型推断 自动(需要部分手动) 完美自动推断
灵活性 较低 更高
代码组织 按类型分组 按功能分组
适用场景 简单 Store 复杂逻辑、需要 watch/生命周期
推荐度 初学友好 官方推荐

选择建议:

  • 新手入门 → Options Store(更清晰)
  • 复杂业务 → Setup Store(更灵活)
  • 团队协作 → 统一使用一种风格

3.4 使用组合式函数构建 Store

Pinia 的 Setup Store 天然支持使用组合式函数:

typescript 复制代码
// composables/useFormValidation.ts
import { ref } from 'vue'

export function useFormValidation() {
  const errors = ref<Record<string, string>>({})
  const isValid = ref(true)
  
  function validateField(field: string, value: any, rules: any[]) {
    // 验证逻辑
  }
  
  function clearErrors() {
    errors.value = {}
    isValid.value = true
  }
  
  return { errors, isValid, validateField, clearErrors }
}
typescript 复制代码
// stores/form.ts
import { defineStore } from 'pinia'
import { useFormValidation } from '@/composables/useFormValidation'

export const useFormStore = defineStore('form', () => {
  // 复用组合式函数
  const { errors, isValid, validateField, clearErrors } = useFormValidation()
  
  // 扩展额外的状态
  const formData = ref({})
  
  function submit() {
    // 提交逻辑
  }
  
  return {
    errors,
    isValid,
    validateField,
    clearErrors,
    formData,
    submit
  }
})

四、State(状态)

4.1 定义 State

在 Options Store 中,state 是一个返回初始状态的函数:

typescript 复制代码
// stores/user.ts
export const useUserStore = defineStore('user', {
  state: () => ({
    // 基本类型
    name: '',
    age: 0,
    isLoggedIn: false,
    // 对象
    profile: {
      email: '',
      avatar: '',
      bio: ''
    },
    // 数组
    permissions: [] as string[],
    // 可空类型
    token: null as string | null
  })
})

在 Setup Store 中,使用 ref 或 reactive:

typescript 复制代码
export const useUserStore = defineStore('user', () => {
  const name = ref('')
  const age = ref(0)
  const isLoggedIn = ref(false)
  const profile = reactive({
    email: '',
    avatar: '',
    bio: ''
  })
  const permissions = ref<string[]>([])
  const token = ref<string | null>(null)
  
  return { name, age, isLoggedIn, profile, permissions, token }
})

4.2 访问 State

在组件中通过 Store 实例访问:

vue 复制代码
<script setup>
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

console.log(userStore.name)        // 直接访问
console.log(userStore.profile)     // 访问对象
</script>

<template>
  <div>
    <p>用户名:{{ userStore.name }}</p>
    <p>年龄:{{ userStore.age }}</p>
    <p>邮箱:{{ userStore.profile.email }}</p>
  </div>
</template>

4.3 修改 State

方式一:直接修改(Pinia 允许直接修改)

vue 复制代码
<script setup>
const userStore = useUserStore()

function updateName() {
  // 直接修改 state
  userStore.name = '张三'
  userStore.age = 30
  userStore.profile.email = 'zhangsan@example.com'
}
</script>

方式二:使用 $patch(批量更新)

vue 复制代码
<script setup>
const userStore = useUserStore()

function updateUser() {
  // 批量修改(推荐,性能更好)
  userStore.$patch({
    name: '张三',
    age: 30,
    profile: {
      ...userStore.profile,
      email: 'zhangsan@example.com'
    }
  })
}

// 使用函数式 patch(更灵活)
function updateUserWithPatchFn() {
  userStore.$patch((state) => {
    state.name = '张三'
    state.age = 30
    state.profile.email = 'zhangsan@example.com'
  })
}
</script>

方式三:通过 Actions

vue 复制代码
<script setup>
const userStore = useUserStore()

// 定义在 actions 中的方法
function login() {
  userStore.login('zhangsan@example.com', 'password')
}
</script>

4.4 响应式解构

从 Store 中解构 state 会丢失响应式:

vue 复制代码
<script setup>
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// ❌ 丢失响应式
const { name, age } = userStore
name = '李四'  // 不会更新 Store

// ✅ 使用 storeToRefs 保持响应式
import { storeToRefs } from 'pinia'
const { name, age } = storeToRefs(userStore)
name.value = '李四'  // 同步更新 Store
</script>

storeToRefs 的作用:

typescript 复制代码
import { storeToRefs } from 'pinia'

const userStore = useUserStore()

// 只提取响应式 state 和 getters
const { name, age, doubleAge } = storeToRefs(userStore)

// Actions 不需要用 storeToRefs
const { login, logout } = userStore

4.5 State 的响应式监听

vue 复制代码
<script setup>
import { watch } from 'vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 监听单个 state
watch(() => userStore.name, (newName) => {
  console.log('用户名变为:', newName)
})

// 监听多个 state
watch(
  () => [userStore.name, userStore.age],
  ([newName, newAge]) => {
    console.log('用户信息变化', newName, newAge)
  }
)

// 监听整个 Store(深层)
watch(
  () => userStore.$state,
  (newState) => {
    console.log('Store 状态变化', newState)
  },
  { deep: true }
)

// 使用 $subscribe 监听变化(推荐)
userStore.$subscribe((mutation, state) => {
  console.log('Store 变化:', mutation)
  console.log('当前状态:', state)
})
</script>

五、Getters(派生状态)

5.1 定义 Getters

Getters 类似于计算属性,用于从 state 派生出新的值。

Options Store:

typescript 复制代码
// stores/product.ts
import { defineStore } from 'pinia'

export const useProductStore = defineStore('product', {
  state: () => ({
    items: [
      { id: 1, name: 'Vue 指南', price: 99, inStock: true },
      { id: 2, name: 'JavaScript 高级', price: 79, inStock: false },
      { id: 3, name: 'TypeScript 实战', price: 89, inStock: true }
    ],
    discount: 0.1,
    searchKeyword: ''
  }),
  
  getters: {
    // 基础 getter:访问 state
    totalCount: (state) => state.items.length,
    
    // 带参数:返回函数
    getProductById: (state) => (id: number) => {
      return state.items.find(item => item.id === id)
    },
    
    // 使用 this 访问其他 getters
    totalPrice: (state) => {
      return state.items.reduce((sum, item) => sum + item.price, 0)
    },
    discountedPrice: (state) => {
      return state.items.reduce((sum, item) => sum + item.price, 0) * (1 - state.discount)
    },
    
    // 参数化的 getter(计算)
    searchProducts: (state) => {
      return (keyword: string) => {
        if (!keyword) return state.items
        return state.items.filter(item => 
          item.name.includes(keyword)
        )
      }
    },
    
    // 组合多个 getter
    summary: (state) => {
      const count = state.items.length
      const total = state.items.reduce((sum, item) => sum + item.price, 0)
      return {
        count,
        total,
        average: count > 0 ? total / count : 0
      }
    }
  }
})

Setup Store:

typescript 复制代码
export const useProductStore = defineStore('product', () => {
  const items = ref([/* ... */])
  const discount = ref(0.1)
  const searchKeyword = ref('')
  
  // 使用 computed 定义 getters
  const totalCount = computed(() => items.value.length)
  
  const totalPrice = computed(() => 
    items.value.reduce((sum, item) => sum + item.price, 0)
  )
  
  const discountedPrice = computed(() => totalPrice.value * (1 - discount.value))
  
  // 参数化 getter(返回函数)
  function getProductById(id: number) {
    return items.value.find(item => item.id === id)
  }
  
  function searchProducts(keyword: string) {
    if (!keyword) return items.value
    return items.value.filter(item => item.name.includes(keyword))
  }
  
  const summary = computed(() => ({
    count: items.value.length,
    total: totalPrice.value,
    average: items.value.length > 0 ? totalPrice.value / items.value.length : 0
  }))
  
  return {
    items,
    discount,
    searchKeyword,
    totalCount,
    totalPrice,
    discountedPrice,
    getProductById,
    searchProducts,
    summary
  }
})

5.2 在组件中使用 Getters

vue 复制代码
<script setup>
import { storeToRefs } from 'pinia'
import { useProductStore } from '@/stores/product'

const productStore = useProductStore()

// 使用 storeToRefs 解构 getters(保持响应式)
const { totalCount, totalPrice, discountedPrice, summary } = storeToRefs(productStore)

// 参数化 getter 直接调用
const product = productStore.getProductById(1)
const searchResults = productStore.searchProducts('Vue')
</script>

<template>
  <div>
    <p>商品总数:{{ totalCount }}</p>
    <p>总价:¥{{ totalPrice }}</p>
    <p>折扣价:¥{{ discountedPrice }}</p>
    <p>平均价格:¥{{ summary.average }}</p>
    
    <div v-if="product">
      <h3>{{ product.name }}</h3>
      <p>价格:¥{{ product.price }}</p>
    </div>
  </div>
</template>

5.3 Getters 的最佳实践

实践 说明
避免副作用 Getter 应该是纯函数,不修改 state
避免异步 Getter 不应该是异步的
参数化 getter 返回函数以支持参数
缓存 Getter 结果被缓存,依赖变化时重新计算
命名清晰 使用描述性名称,如 totalPrice、activeUsers

六、Actions(修改状态)

6.1 定义 Actions

Actions 是包含业务逻辑的方法,用于修改 state(支持同步和异步)。

Options Store:

typescript 复制代码
// stores/user.ts
import { defineStore } from 'pinia'
import { api } from '@/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    token: null as string | null,
    isLoading: false,
    error: null as string | null
  }),
  
  actions: {
    // 同步 action
    setUser(user: User) {
      this.user = user
    },
    
    // 异步 action
    async login(email: string, password: string) {
      this.isLoading = true
      this.error = null
      
      try {
        const response = await api.login(email, password)
        this.user = response.user
        this.token = response.token
        // 持久化存储
        localStorage.setItem('token', response.token)
        return response
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    async logout() {
      this.user = null
      this.token = null
      localStorage.removeItem('token')
    },
    
    // 调用其他 action
    async refreshUser() {
      if (!this.token) return
      try {
        const user = await api.getCurrentUser(this.token)
        this.user = user
      } catch (error) {
        this.logout()  // token 失效,自动登出
        throw error
      }
    }
  }
})

Setup Store:

typescript 复制代码
export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  
  function setUser(newUser: User) {
    user.value = newUser
  }
  
  async function login(email: string, password: string) {
    isLoading.value = true
    error.value = null
    
    try {
      const response = await api.login(email, password)
      user.value = response.user
      token.value = response.token
      localStorage.setItem('token', response.token)
      return response
    } catch (err) {
      error.value = err.message
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  async function logout() {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
  }
  
  async function refreshUser() {
    if (!token.value) return
    try {
      const data = await api.getCurrentUser(token.value)
      user.value = data
    } catch {
      logout()
    }
  }
  
  return {
    user,
    token,
    isLoading,
    error,
    setUser,
    login,
    logout,
    refreshUser
  }
})

6.2 在组件中使用 Actions

vue 复制代码
<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const email = ref('')
const password = ref('')
const loading = ref(false)

async function handleLogin() {
  try {
    await userStore.login(email.value, password.value)
    // 登录成功跳转
    router.push('/dashboard')
  } catch (error) {
    // 显示错误
    console.error('登录失败', error)
  }
}

function handleLogout() {
  userStore.logout()
  router.push('/login')
}
</script>

<template>
  <form @submit.prevent="handleLogin">
    <input v-model="email" type="email" placeholder="邮箱" />
    <input v-model="password" type="password" placeholder="密码" />
    <button type="submit" :disabled="userStore.isLoading">
      {{ userStore.isLoading ? '登录中...' : '登录' }}
    </button>
    <p v-if="userStore.error" class="error">{{ userStore.error }}</p>
  </form>
</template>

6.3 Actions 的响应式访问

vue 复制代码
<script setup>
import { useUserStore } from '@/stores/user'

// 直接解构 actions(不会丢失响应式,因为 actions 是函数)
const { login, logout, refreshUser } = useUserStore()

// 或者整个 Store
const userStore = useUserStore()
</script>

6.4 Actions 之间的相互调用

typescript 复制代码
// stores/order.ts
export const useOrderStore = defineStore('order', {
  state: () => ({
    orders: [] as Order[],
    currentOrder: null as Order | null
  }),
  
  actions: {
    // 调用其他 Store 的 action
    async createOrder(orderData: OrderData) {
      const userStore = useUserStore()
      
      if (!userStore.user) {
        throw new Error('请先登录')
      }
      
      const order = await api.createOrder({
        ...orderData,
        userId: userStore.user.id
      })
      
      this.orders.push(order)
      this.currentOrder = order
      
      return order
    },
    
    // 调用自己 Store 的其他 action
    async syncOrders() {
      await this.fetchOrders()
      await this.updatePendingOrders()
    },
    
    async fetchOrders() {
      // ...
    },
    
    async updatePendingOrders() {
      // ...
    }
  }
})

七、Store 之间的交互

7.1 在一个 Store 中访问另一个 Store

typescript 复制代码
// stores/cart.ts
import { defineStore } from 'pinia'
import { useUserStore } from './user'
import { useProductStore } from './product'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [] as CartItem[]
  }),
  
  getters: {
    totalItems: (state) => state.items.reduce((sum, item) => sum + item.quantity, 0),
    
    totalPrice: (state) => {
      const productStore = useProductStore()
      return state.items.reduce((sum, item) => {
        const product = productStore.getProductById(item.productId)
        return sum + (product?.price || 0) * item.quantity
      }, 0)
    },
    
    // 检查商品是否在购物车中
    isInCart: (state) => (productId: number) => {
      return state.items.some(item => item.productId === productId)
    }
  },
  
  actions: {
    addToCart(productId: number, quantity: number = 1) {
      const existingItem = this.items.find(item => item.productId === productId)
      
      if (existingItem) {
        existingItem.quantity += quantity
      } else {
        this.items.push({ productId, quantity })
      }
      
      // 调用其他 Store 的 action(记录用户行为)
      const userStore = useUserStore()
      if (userStore.user) {
        userStore.trackAction('add_to_cart', { productId, quantity })
      }
    },
    
    async checkout() {
      const userStore = useUserStore()
      const orderStore = useOrderStore()
      
      if (!userStore.user) {
        throw new Error('请先登录')
      }
      
      if (this.items.length === 0) {
        throw new Error('购物车为空')
      }
      
      // 创建订单
      const order = await orderStore.createOrder({
        items: this.items,
        totalPrice: this.totalPrice
      })
      
      // 清空购物车
      this.items = []
      
      return order
    }
  }
})

7.2 循环依赖的处理

Pinia 支持 Store 之间的循环依赖,但需要注意:

typescript 复制代码
// 使用 getter 延迟获取依赖
getters: {
  userInfo: (state) => {
    // 在 getter 中使用 useUserStore
    const userStore = useUserStore()
    return {
      ...state,
      userName: userStore.user?.name
    }
  }
}

// 在 action 中使用依赖
actions: {
  async doSomething() {
    const userStore = useUserStore()
    // 使用 userStore...
  }
}

八、综合实战:购物车与用户系统

让我们构建一个完整的购物车应用,整合所有 Pinia 知识:

typescript 复制代码
// types/index.ts
export interface User {
  id: number
  name: string
  email: string
  address: string
}

export interface Product {
  id: number
  name: string
  price: number
  description: string
  image: string
  stock: number
}

export interface CartItem {
  productId: number
  quantity: number
  selected?: boolean
}

export interface Order {
  id: number
  userId: number
  items: CartItem[]
  totalPrice: number
  status: 'pending' | 'paid' | 'shipped' | 'delivered'
  createdAt: Date
}
typescript 复制代码
// stores/product.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Product } from '@/types'
import { api } from '@/api'

export const useProductStore = defineStore('product', () => {
  // State
  const products = ref<Product[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const searchKeyword = ref('')
  
  // Getters
  const filteredProducts = computed(() => {
    if (!searchKeyword.value.trim()) {
      return products.value
    }
    const keyword = searchKeyword.value.toLowerCase()
    return products.value.filter(p => 
      p.name.toLowerCase().includes(keyword) ||
      p.description.toLowerCase().includes(keyword)
    )
  })
  
  const inStockProducts = computed(() => 
    products.value.filter(p => p.stock > 0)
  )
  
  const getProductById = (id: number) => {
    return products.value.find(p => p.id === id)
  }
  
  // Actions
  async function fetchProducts() {
    isLoading.value = true
    error.value = null
    try {
      const data = await api.getProducts()
      products.value = data
    } catch (err) {
      error.value = err.message
    } finally {
      isLoading.value = false
    }
  }
  
  function setSearchKeyword(keyword: string) {
    searchKeyword.value = keyword
  }
  
  function updateStock(productId: number, quantity: number) {
    const product = products.value.find(p => p.id === productId)
    if (product) {
      product.stock = Math.max(0, product.stock - quantity)
    }
  }
  
  return {
    // State
    products,
    isLoading,
    error,
    searchKeyword,
    // Getters
    filteredProducts,
    inStockProducts,
    getProductById,
    // Actions
    fetchProducts,
    setSearchKeyword,
    updateStock
  }
})
typescript 复制代码
// stores/cart.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useProductStore } from './product'
import { useUserStore } from './user'
import type { CartItem } from '@/types'

export const useCartStore = defineStore('cart', () => {
  // State
  const items = ref<CartItem[]>([])
  
  // Getters
  const totalItems = computed(() => 
    items.value.reduce((sum, item) => sum + item.quantity, 0)
  )
  
  const selectedItems = computed(() => 
    items.value.filter(item => item.selected !== false)
  )
  
  const selectedCount = computed(() => 
    selectedItems.value.reduce((sum, item) => sum + item.quantity, 0)
  )
  
  const totalPrice = computed(() => {
    const productStore = useProductStore()
    return selectedItems.value.reduce((sum, item) => {
      const product = productStore.getProductById(item.productId)
      return sum + (product?.price || 0) * item.quantity
    }, 0)
  })
  
  const isInCart = (productId: number) => {
    return items.value.some(item => item.productId === productId)
  }
  
  const getItemQuantity = (productId: number) => {
    const item = items.value.find(i => i.productId === productId)
    return item?.quantity || 0
  }
  
  // Actions
  function addToCart(productId: number, quantity: number = 1) {
    const productStore = useProductStore()
    const product = productStore.getProductById(productId)
    
    if (!product) {
      throw new Error('商品不存在')
    }
    
    if (product.stock < quantity) {
      throw new Error('库存不足')
    }
    
    const existingItem = items.value.find(item => item.productId === productId)
    
    if (existingItem) {
      if (product.stock < existingItem.quantity + quantity) {
        throw new Error('库存不足')
      }
      existingItem.quantity += quantity
    } else {
      items.value.push({ 
        productId, 
        quantity, 
        selected: true 
      })
    }
    
    // 更新库存
    productStore.updateStock(productId, quantity)
  }
  
  function removeFromCart(productId: number) {
    const index = items.value.findIndex(item => item.productId === productId)
    if (index !== -1) {
      const item = items.value[index]
      // 归还库存
      const productStore = useProductStore()
      productStore.updateStock(productId, -item.quantity)
      
      items.value.splice(index, 1)
    }
  }
  
  function updateQuantity(productId: number, quantity: number) {
    const item = items.value.find(i => i.productId === productId)
    if (!item) return
    
    const productStore = useProductStore()
    const product = productStore.getProductById(productId)
    
    if (!product) return
    
    const diff = quantity - item.quantity
    
    if (diff > 0 && product.stock < diff) {
      throw new Error('库存不足')
    }
    
    if (quantity <= 0) {
      removeFromCart(productId)
      return
    }
    
    item.quantity = quantity
    productStore.updateStock(productId, diff)
  }
  
  function toggleSelect(productId: number) {
    const item = items.value.find(i => i.productId === productId)
    if (item) {
      item.selected = !item.selected
    }
  }
  
  function selectAll(selected: boolean) {
    items.value.forEach(item => {
      item.selected = selected
    })
  }
  
  function clearCart() {
    // 归还所有库存
    items.value.forEach(item => {
      const productStore = useProductStore()
      productStore.updateStock(item.productId, -item.quantity)
    })
    items.value = []
  }
  
  async function checkout() {
    const userStore = useUserStore()
    const orderStore = useOrderStore()
    
    if (!userStore.user) {
      throw new Error('请先登录')
    }
    
    if (selectedItems.value.length === 0) {
      throw new Error('请选择至少一件商品')
    }
    
    // 创建订单
    const order = await orderStore.createOrder({
      userId: userStore.user.id,
      items: selectedItems.value,
      totalPrice: totalPrice.value
    })
    
    // 从购物车中移除已购买的商品
    const selectedIds = selectedItems.value.map(item => item.productId)
    items.value = items.value.filter(item => !selectedIds.includes(item.productId))
    
    return order
  }
  
  return {
    // State
    items,
    // Getters
    totalItems,
    selectedItems,
    selectedCount,
    totalPrice,
    isInCart,
    getItemQuantity,
    // Actions
    addToCart,
    removeFromCart,
    updateQuantity,
    toggleSelect,
    selectAll,
    clearCart,
    checkout
  }
})
typescript 复制代码
// stores/order.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Order } from '@/types'
import { api } from '@/api'

export const useOrderStore = defineStore('order', () => {
  const orders = ref<Order[]>([])
  const isLoading = ref(false)
  
  const recentOrders = computed(() => 
    [...orders.value].sort((a, b) => 
      new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    ).slice(0, 5)
  )
  
  async function createOrder(orderData: Omit<Order, 'id' | 'createdAt' | 'status'>) {
    isLoading.value = true
    try {
      const order = await api.createOrder(orderData)
      orders.value.push(order)
      return order
    } finally {
      isLoading.value = false
    }
  }
  
  async function fetchOrders(userId: number) {
    isLoading.value = true
    try {
      const data = await api.getOrders(userId)
      orders.value = data
    } finally {
      isLoading.value = false
    }
  }
  
  return {
    orders,
    isLoading,
    recentOrders,
    createOrder,
    fetchOrders
  }
})

在组件中使用:

vue 复制代码
<!-- CartView.vue -->
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useCartStore } from '@/stores/cart'
import { useProductStore } from '@/stores/product'
import { useUserStore } from '@/stores/user'
import { ref } from 'vue'

const cartStore = useCartStore()
const productStore = useProductStore()
const userStore = useUserStore()

// 使用 storeToRefs 解构响应式数据
const { items, totalItems, selectedItems, totalPrice, selectedCount } = storeToRefs(cartStore)
const { user } = storeToRefs(userStore)

// Actions 可以直接解构
const { toggleSelect, selectAll, removeFromCart, updateQuantity, checkout } = cartStore

const isCheckingOut = ref(false)

// 获取商品详情
function getProduct(productId: number) {
  return productStore.getProductById(productId)
}

// 格式化价格
function formatPrice(price: number) {
  return `¥${price.toFixed(2)}`
}

// 结算
async function handleCheckout() {
  if (!user.value) {
    alert('请先登录')
    return
  }
  
  isCheckingOut.value = true
  try {
    const order = await checkout()
    alert(`订单创建成功!订单号:#${order.id}`)
  } catch (error) {
    alert(error.message)
  } finally {
    isCheckingOut.value = false
  }
}
</script>

<template>
  <div class="cart-page">
    <h1>🛒 购物车</h1>
    
    <div v-if="items.length === 0" class="empty-cart">
      <p>购物车是空的</p>
      <RouterLink to="/products">去逛逛</RouterLink>
    </div>
    
    <template v-else>
      <!-- 全选 -->
      <div class="cart-actions">
        <label>
          <input 
            type="checkbox" 
            :checked="items.every(item => item.selected !== false)"
            @change="selectAll(($event.target as HTMLInputElement).checked)"
          />
          全选
        </label>
        <span>共 {{ totalItems }} 件商品</span>
        <span>已选 {{ selectedCount }} 件</span>
      </div>
      
      <!-- 商品列表 -->
      <div class="cart-items">
        <div 
          v-for="item in items" 
          :key="item.productId"
          class="cart-item"
        >
          <input 
            type="checkbox"
            :checked="item.selected !== false"
            @change="toggleSelect(item.productId)"
          />
          
          <div class="item-info">
            <img 
              :src="getProduct(item.productId)?.image" 
              :alt="getProduct(item.productId)?.name"
              class="item-image"
            />
            <div>
              <h3>{{ getProduct(item.productId)?.name }}</h3>
              <p class="item-price">{{ formatPrice(getProduct(item.productId)?.price || 0) }}</p>
            </div>
          </div>
          
          <div class="item-controls">
            <button 
              @click="updateQuantity(item.productId, item.quantity - 1)"
              :disabled="item.quantity <= 1"
            >−</button>
            <span>{{ item.quantity }}</span>
            <button 
              @click="updateQuantity(item.productId, item.quantity + 1)"
              :disabled="(getProduct(item.productId)?.stock || 0) <= 0"
            >+</button>
            <button @click="removeFromCart(item.productId)" class="remove-btn">🗑️</button>
          </div>
        </div>
      </div>
      
      <!-- 结算 -->
      <div class="cart-summary">
        <div>
          <span>合计:</span>
          <span class="total-price">{{ formatPrice(totalPrice) }}</span>
        </div>
        <button 
          @click="handleCheckout" 
          :disabled="selectedItems.length === 0 || isCheckingOut"
          class="checkout-btn"
        >
          {{ isCheckingOut ? '处理中...' : `结算 (${selectedCount} 件)` }}
        </button>
      </div>
    </template>
  </div>
</template>

<style scoped>
.cart-page {
  max-width: 800px;
  margin: 20px auto;
  padding: 24px;
}
.empty-cart {
  text-align: center;
  padding: 60px 20px;
}
.empty-cart a {
  color: #4299e1;
  text-decoration: none;
}

.cart-actions {
  display: flex;
  gap: 20px;
  padding: 12px 0;
  border-bottom: 1px solid #e2e8f0;
}

.cart-items {
  margin: 16px 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.cart-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f7fafc;
  border-radius: 10px;
  transition: background 0.2s;
}
.cart-item:hover { background: #edf2f7; }

.item-info {
  display: flex;
  gap: 16px;
  flex: 1;
  align-items: center;
}
.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 8px;
}
.item-price { color: #2b6cb0; font-weight: 600; }

.item-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}
.item-controls button {
  width: 30px;
  height: 30px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background: white;
  cursor: pointer;
}
.item-controls button:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}
.remove-btn {
  border: none !important;
  background: none !important;
}

.cart-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-top: 2px solid #e2e8f0;
  font-size: 18px;
}
.total-price {
  font-size: 24px;
  font-weight: 700;
  color: #2b6cb0;
}
.checkout-btn {
  padding: 12px 32px;
  background: #4299e1;
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
}
.checkout-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>

九、本篇小结

知识点 核心内容
Pinia 优势 无 Mutations、完美 TS、扁平结构、轻量
创建 Store defineStore(id, options)
Options Store state + getters + actions
Setup Store ref + computed + functions
State 直接修改、$patch、$subscribe
Getters 派生状态,类似 computed
Actions 修改状态的方法,支持异步
storeToRefs 保持解构后的响应式
Store 交互 在 Store 中调用其他 Store

十、思考与练习

  1. 基础练习 :创建一个 theme Store,管理应用的主题配置(深色/浅色模式、主色调等),并提供切换方法。

  2. 实践任务:在购物车示例基础上,增加"优惠券"功能。用户输入优惠码后,根据优惠码类型(满减、折扣)计算新的总价。

  3. 深度思考:Pinia 为什么移除了 Vuex 中的 Mutations?这种设计对代码的可维护性和调试有什么影响?

  4. 扩展任务 :使用 $subscribe 实现购物车数据的持久化,当商品加入购物车时自动保存到 localStorage,页面刷新后恢复购物车状态。

下篇预告

第 23 篇我们将继续学习 Pinia 高级特性:

  • Store 之间的相互调用
  • 持久化存储方案(pinia-plugin-persistedstate)
  • Pinia 与 TypeScript 的深度配合
  • Vue DevTools 调试技巧
  • Pinia 插件开发

准备好掌握 Pinia 的生产级使用技巧!🚀

相关推荐
bai27337 分钟前
"👨‍👩‍👧‍👦" 的 length 是 11:我把自己写的字数统计脚本拖出来审了一遍
前端·javascript
bai2731 小时前
同一个 1.005,toFixed 给 1.00、Math.round 给 1、Intl 给 1.01:999 个三分位小数的实测
javascript·后端
爱编程的171 小时前
一篇讲透 JS 对象:数据类型、原型链与包装类
javascript
zhanlang02172 小时前
HTML 零基础入门到企业实战【第八章 8.5】画布 canvas、SVG 矢量图形基础入门
前端·html
星云_byto3 小时前
CSS面试题
前端·css
zhanlang02173 小时前
HTML 零基础入门到企业实战全套教程【连载 8.4】HTML5 新增表单属性与表单控件
前端·html·html5
Highcharts.js7 小时前
Highcharts漏斗图表使用配置指南
java·开发语言·javascript·信息可视化·highcharts·漏斗图
科研邪修法11 小时前
PDF新增页面文字与文本批注怎么区分?以双版本培训讲义为例
前端·css·pdf
武昌库里写JAVA11 小时前
SpringBoot+Vue 项目介绍
java·javascript·git·sql·ai