8.1 深度集成 Vue 生态
8.1.1 与 Vue Router 联动
import type { RouteLocationNormalized } from 'vue-router'
export const useRouterStore = defineStore('router', {
state: () => ({
navigationHistory: [] as RouteLocationNormalized[],
currentTransition: null as string | null
}),
actions: {
trackNavigation(to: RouteLocationNormalized) {
if (this.navigationHistory.length > 50) {
this.navigationHistory.shift()
}
this.navigationHistory.push(to)
},
setTransition(effect: string) {
this.currentTransition = effect
}
}
})
router.beforeEach((to, from) => {
const store = useRouterStore()
store.trackNavigation(from)
if (to.meta.transition) {
store.setTransition(to.meta.transition)
}
})
8.1.2 整合 Vue Query
import { useQuery } from 'vue-query'
export const useApiStore = defineStore('api', () => {
const fetchUser = async (userId: string) => {
const res = await axios.get(`/users/${userId}`)
return res.data
}
const {
data: user,
isLoading,
error
} = useQuery(['user', userId], () => fetchUser(userId), {
staleTime: 5 * 60 * 1000
})
return {
user,
isLoading,
error
}
})
const { user, isLoading } = useApiStore()
8.2 微前端架构实践
8.2.1 跨应用状态共享
export const useSharedStore = defineStore('shared', {
state: () => ({
globalConfig: {} as AppConfig,
microStores: new Map<string, any>()
}),
actions: {
registerMicroStore(name: string, store: any) {
this.microStores.set(name, store)
}
}
})
window.connectToHost = (hostStore: any) => {
const localStore = useMicroStore()
hostStore.registerMicroStore('microApp', {
state: localStore.$state,
actions: pick(localStore, ['fetchData', 'submitForm'])
})
}
8.2.2 状态隔离方案
function createSandboxedPinia() {
const pinia = createPinia()
const originalPatch = pinia._p.push
pinia._p.push = (plugin) => {
if (plugin.name !== 'sandboxed') return
originalPatch.call(pinia, plugin)
}
return pinia
}
const sandboxedPinia = createSandboxedPinia()
app.use(sandboxedPinia)
8.3 状态管理未来趋势
8.3.1 响应式关系型数据
import { Database } from '@nozbe/watermelondb'
import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite'
export const useDatabaseStore = defineStore('database', () => {
const adapter = new SQLiteAdapter({
schema: require('./schema.json')
})
const database = new Database({
adapter,
modelClasses: [User, Post]
})
const users = database.collections.get('users')
const posts = database.collections.get('posts')
async function queryUserPosts(userId: string) {
return await users.find(userId).posts.fetch()
}
return {
database,
users,
posts,
queryUserPosts
}
})
8.3.2 原子化状态管理
import { atom, useAtom } from 'jotai'
const countAtom = atom(0)
const doubledAtom = atom((get) => get(countAtom) * 2)
export const useCounterStore = defineStore('counter', () => {
const [count, setCount] = useAtom(countAtom)
const [doubled] = useAtom(doubledAtom)
function increment() {
setCount((prev) => prev + 1)
}
return {
count,
doubled,
increment
}
})
8.4 多语言国际化方案
8.4.1 集成 i18n
import { createI18n } from 'vue-i18n'
export const useI18nStore = defineStore('i18n', {
state: () => ({
locale: 'zh-CN',
messages: {} as Record<string, any>
}),
actions: {
async switchLocale(newLocale: string) {
if (!this.messages[newLocale]) {
this.messages[newLocale] = await import(`../locales/${newLocale}.json`)
}
this.locale = newLocale
}
},
getters: {
t: (state) => (key: string) => {
return state.messages[state.locale]?.[key] || key
}
}
})
const i18n = createI18n({
legacy: false,
locale: useI18nStore().locale,
messages: useI18nStore().messages
})
8.5 性能优化终极策略
8.5.1 Web Worker 集成
export const useWorkerStore = defineStore('worker', () => {
const worker = new Worker('./heavy-task.js')
const result = ref(null)
const isProcessing = ref(false)
worker.onmessage = (e) => {
result.value = e.data
isProcessing.value = false
}
function processData(data: any) {
isProcessing.value = true
worker.postMessage(data)
}
return {
result,
isProcessing,
processData
}
})
self.onmessage = function(e) {
const result = performHeavyCalculation(e.data)
self.postMessage(result)
}
8.5.2 WASM 加速计算
export const useWasmStore = defineStore('wasm', () => {
const instance = ref<WebAssembly.Instance | null>(null)
async function init() {
const response = await fetch('optimized.wasm')
const buffer = await response.arrayBuffer()
const module = await WebAssembly.compile(buffer)
instance.value = await WebAssembly.instantiate(module)
}
function complexCalculation(input: number) {
if (!instance.value) throw new Error('WASM 未初始化')
return instance.value.exports.calculate(input)
}
return {
init,
complexCalculation
}
})
本章核心总结:
- 生态融合:深度整合 Vue Router、Vue Query 等核心生态库
- 架构演进:
- 未来方向:
- 国际化方案:动态语言包加载与响应式切换
- 极致性能:
- Web Worker 分流计算
- WASM 性能加速
- 内存敏感型操作优化