Vue3原子化状态管理:Pinia高级模式与性能优化实战

2025-07-14 0 737

Vue3原子化状态管理:Pinia高级模式与性能优化实战

一、原子化Store设计理念

将全局状态拆分为小型、专注的Store模块,每个Store只管理单一业务领域的状态。

// stores/auth.store.js
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: '',
    permissions: []
  }),
  actions: {
    async login(credentials) {
      const { data } = await api.login(credentials)
      this.user = data.user
      this.token = data.token
      this.permissions = data.permissions
    }
  },
  getters: {
    isAdmin: (state) => state.permissions.includes('admin')
  }
})

// stores/ui.store.js
export const useUIStore = defineStore('ui', {
  state: () => ({
    theme: 'light',
    sidebarCollapsed: false,
    loading: false
  }),
  actions: {
    toggleTheme() {
      this.theme = this.theme === 'light' ? 'dark' : 'light'
    }
  }
})

二、高级模式实战

1. Store组合与复用

// stores/cart.store.js
export const useCartStore = defineStore('cart', () => {
  const items = ref([])
  const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0))
  
  function addItem(product) {
    const existing = items.value.find(item => item.id === product.id)
    existing ? existing.quantity++ : items.value.push({ ...product, quantity: 1 })
  }
  
  return { items, total, addItem }
})

// stores/checkout.store.js
export const useCheckoutStore = defineStore('checkout', () => {
  const cartStore = useCartStore()
  const shipping = ref(null)
  
  const grandTotal = computed(() => {
    return cartStore.total + (shipping.value?.price || 0)
  })
  
  return { shipping, grandTotal }
})

2. 持久化与SSR集成

// 持久化插件
export function persistPlugin({ store }) {
  const key = `pinia-${store.$id}`
  
  // 从本地存储恢复
  const saved = localStorage.getItem(key)
  if (saved) {
    store.$patch(JSON.parse(saved))
  }
  
  // 订阅变化
  store.$subscribe((mutation, state) => {
    localStorage.setItem(key, JSON.stringify(state))
  })
}

// SSR集成示例
export default {
  install(app) {
    const pinia = createPinia()
    
    if (process.server) {
      pinia.use(({ store }) => {
        store.$ssrContext = useContext()
      })
    }
    
    pinia.use(persistPlugin)
    app.use(pinia)
  }
}

三、电商系统实战案例

// stores/product.store.js
export const useProductStore = defineStore('products', {
  state: () => ({
    products: [],
    featured: [],
    categories: []
  }),
  actions: {
    async fetchProducts() {
      const [products, featured] = await Promise.all([
        api.get('/products'),
        api.get('/products/featured')
      ])
      
      this.products = products
      this.featured = featured
      this.categories = [...new Set(products.map(p => p.category))]
    },
    async searchProducts(query) {
      const { data } = await api.get('/products/search', { params: { q: query } })
      return data
    }
  },
  getters: {
    getByCategory: (state) => (category) => {
      return state.products.filter(p => p.category === category)
    }
  }
})

// 在组件中使用
import { storeToRefs } from 'pinia'

export default {
  setup() {
    const productStore = useProductStore()
    const { featured, categories } = storeToRefs(productStore)
    
    onMounted(() => {
      productStore.fetchProducts()
    })
    
    return { featured, categories }
  }
}

四、性能优化策略

  • 细粒度订阅:使用storeToRefs避免不必要的响应式转换
  • 批量更新:使用$patch合并多个状态变更
  • 惰性加载:动态导入大型Store模块
  • 缓存策略:为API数据添加缓存时间戳
  • 内存管理:及时清理不再使用的Store实例
Vue3原子化状态管理:Pinia高级模式与性能优化实战
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

淘吗网 vue3 Vue3原子化状态管理:Pinia高级模式与性能优化实战 https://www.taomawang.com/web/vue3/345.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务