4.1 模块化设计原则
4.1.1 项目结构规范
src/
├─ stores/
│ ├─ modules/
│ │ ├─ auth.store.ts # 认证相关状态
│ │ ├─ cart.store.ts # 购物车管理
│ │ ├─ product.store.ts # 商品数据
│ │ └─ ui.store.ts # UI 全局状态
│ ├─ shared/
│ │ ├─ api.client.ts # 封装的请求客户端
│ │ └─ cache.utils.ts # 缓存工具函数
│ └─ index.ts # 统一导出入口
模块划分策略:
- 按业务领域拆分(用户、商品、订单等)
- 按功能类型划分(数据层、UI 层、配置层)
- 共享工具统一管理(请求库、本地存储等)
4.1.2 统一导出模式
// stores/index.ts
export { useAuthStore } from './modules/auth.store'
export { useCartStore } from './modules/cart.store'
export { useProductStore } from './modules/product.store'
export { useUIStore } from './modules/ui.store'
// 组件中使用:
import { useAuthStore, useCartStore } from '@/stores'
4.2 Store 间通信模式
4.2.1 直接引用模式
// modules/cart.store.ts
export const useCartStore = defineStore('cart', {
actions: {
async checkout() {
const authStore = useAuthStore()
const uiStore = useUIStore()
if (!authStore.isLoggedIn) {
uiStore.showLoginModal() // 触发 UI 变更
throw new Error('需要登录')
}
await this.validateStock()
await this.processPayment()
}
}
})
4.2.2 事件总线模式
// shared/event-bus.ts
import mitt from 'mitt'
type Events = {
'cart:updated': CartItem[]
'auth:loggedIn': UserProfile
}
export const bus = mitt<Events>()
// modules/cart.store.ts
bus.emit('cart:updated', this.items)
// modules/analytics.store.ts
bus.on('cart:updated', (items) => {
this.trackEvent('cart_update', { itemCount: items.length })
})
4.2.3 共享根 Store
// modules/core.store.ts
export const useCoreStore = defineStore('core', {
state: () => ({
appVersion: '1.0.0',
config: {} as AppConfig
}),
actions: {
async loadConfig() {
this.config = await fetchConfig()
}
}
})
// 其他 Store 中使用
const coreStore = useCoreStore()
const apiClient = createClient(coreStore.config.apiBase)
4.3 高级组合模式
4.3.1 组合函数封装
// composables/useCheckout.ts
export function useCheckout() {
const cart = useCartStore()
const user = useUserStore()
const router = useRouter()
// 私有状态
const loading = ref(false)
const error = ref<Error | null>(null)
async function execute() {
try {
loading.value = true
await cart.validate()
await user.validatePayment()
const result = await cart.submitOrder()
router.push(`/orders/${result.orderId}`)
} catch (err) {
error.value = err
throw err
} finally {
loading.value = false
}
}
return {
execute,
loading,
error
}
}
// 组件中使用:
const { execute, loading } = useCheckout()
4.3.2 跨 Store 状态同步
// plugins/sync.ts
export const createSyncPlugin = (sourceStoreId: string, targetStoreId: string, keys: string[]) => {
return ({ pinia }) => {
const source = pinia._s.get(sourceStoreId)
const target = pinia._s.get(targetStoreId)
source.$subscribe((_, state) => {
const partial = keys.reduce((obj, key) => {
obj[key] = state[key]
return obj
}, {})
target.$patch(partial)
})
}
}
// 使用示例(同步用户基础信息)
pinia.use(createSyncPlugin('user', 'profile', ['name', 'avatar']))
4.4 动态模块注册
4.4.1 按需加载 Store
// stores/lazy.ts
const dynamicStores = new Map<string, Promise<any>>()
export async function useDynamicStore<T>(id: string, loader: () => Promise<T>): Promise<T> {
if (!dynamicStores.has(id)) {
dynamicStores.set(id, loader())
}
return dynamicStores.get(id)!
}
// 组件中使用
const adminStore = await useDynamicStore('admin', () => import('./modules/admin.store'))
4.4.2 运行时注册 Store
// utils/registerStore.ts
export function registerStore(id: string, definition: StoreDefinition) {
const pinia = usePinia()
if (!pinia._s.has(id)) {
pinia._s.set(id, defineStore(id, definition)())
}
return pinia._s.get(id)
}
// 动态注册示例
registerStore('experimental', {
state: () => ({ features: [] }),
actions: {
toggleFeature(name: string) {
// ...
}
}
})
4.5 微前端场景实践
4.5.1 主应用配置
// main-app/src/stores/shared.ts
export const useSharedStore = defineStore('shared', {
state: () => ({
globalToken: '',
microfrontends: {} as Record<string, any>
}),
actions: {
registerMicroStore(name: string, store: any) {
this.microfrontends[name] = store
}
}
})
4.5.2 子应用集成
// micro-app/src/stores/local.ts
export const useMicroStore = defineStore('micro', {
actions: {
init(sharedStore: any) {
sharedStore.registerMicroStore('microApp', {
getData: this.fetchData,
reset: this.clearCache
})
}
}
})
// 子应用挂载时
const sharedStore = window.parent.getSharedStore()
useMicroStore().init(sharedStore)
本章核心总结:
- 模块化架构:采用垂直切割(按业务)与水平分层(按功能)结合的方式
- 通信模式选择:
- 直接引用:简单场景
- 事件总线:解耦模块
- 共享核心:基础数据
- 组合模式:
- 使用 Composables 封装复杂逻辑
- 通过插件实现自动同步
- 动态能力:
- 按需加载提升性能
- 运行时注册增强扩展性
- 微前端集成:通过共享 Store 实现跨应用状态管理