优化pinia持久化

This commit is contained in:
2026-01-15 09:51:59 +08:00
parent bb1ed16d8b
commit ab737f8a75
9 changed files with 239 additions and 155 deletions
+26 -25
View File
@@ -1,34 +1,35 @@
import { defineStore } from 'pinia'
import i18n from '@/i18n'
export const useI18nStore = defineStore('i18n', {
state: () => ({
currentLocale: 'zh-CN',
availableLocales: [
{ label: '简体中文', value: 'zh-CN' },
{ label: 'English', value: 'en-US' }
]
}),
export const useI18nStore = defineStore(
'i18n',
{
state: () => ({
currentLocale: 'zh-CN',
availableLocales: [
{ label: '简体中文', value: 'zh-CN' },
{ label: 'English', value: 'en-US' }
]
}),
getters: {
localeLabel: (state) => {
const locale = state.availableLocales.find((item) => item.value === state.currentLocale)
return locale ? locale.label : ''
}
},
actions: {
setLocale(locale) {
this.currentLocale = locale
i18n.global.locale.value = locale
localStorage.setItem('locale', locale)
getters: {
localeLabel: (state) => {
const locale = state.availableLocales.find((item) => item.value === state.currentLocale)
return locale ? locale.label : ''
}
},
initLocale() {
const savedLocale = localStorage.getItem('locale')
if (savedLocale && this.availableLocales.some((item) => item.value === savedLocale)) {
this.setLocale(savedLocale)
actions: {
setLocale(locale) {
this.currentLocale = locale
i18n.global.locale.value = locale
}
},
persist: {
key: 'i18n-store',
storage: localStorage,
pick: ['currentLocale']
}
}
})
)