58 lines
1.5 KiB
JavaScript
58 lines
1.5 KiB
JavaScript
import { defineStore } from 'pinia'
|
||
import { ref } from 'vue'
|
||
import i18n, { SUPPORTED_LOCALES, DEFAULT_LOCALE } from '../i18n/index.js'
|
||
import { getStorage, setStorage, LOCALE_KEY } from '../utils/storage.js'
|
||
|
||
export const useAppStore = defineStore('app', () => {
|
||
const locale = ref(DEFAULT_LOCALE)
|
||
|
||
/**
|
||
* 切换语言,同步更新i18n并持久化到本地存储
|
||
* @param {string} newLocale - 目标语言标识
|
||
*/
|
||
function setLocale(newLocale) {
|
||
if (!SUPPORTED_LOCALES.includes(newLocale)) {
|
||
return
|
||
}
|
||
locale.value = newLocale
|
||
i18n.global.locale.value = newLocale
|
||
setStorage(LOCALE_KEY, newLocale)
|
||
}
|
||
|
||
/**
|
||
* 初始化语言:优先从本地存储读取,否则根据系统语言匹配
|
||
*/
|
||
function initLocale() {
|
||
const savedLocale = getStorage(LOCALE_KEY)
|
||
if (savedLocale && SUPPORTED_LOCALES.includes(savedLocale)) {
|
||
setLocale(savedLocale)
|
||
return
|
||
}
|
||
|
||
// 从系统语言推断
|
||
let systemLocale = DEFAULT_LOCALE
|
||
try {
|
||
const systemInfo = uni.getSystemInfoSync()
|
||
const lang = systemInfo.language || ''
|
||
if (lang.startsWith('zh')) {
|
||
// 区分简体和繁体
|
||
systemLocale = lang.includes('TW') || lang.includes('HK') || lang.includes('Hant')
|
||
? 'zh-TW'
|
||
: 'zh-CN'
|
||
} else if (lang.startsWith('en')) {
|
||
systemLocale = 'en'
|
||
}
|
||
} catch (e) {
|
||
// 获取系统信息失败,使用默认语言
|
||
}
|
||
|
||
setLocale(systemLocale)
|
||
}
|
||
|
||
return {
|
||
locale,
|
||
setLocale,
|
||
initLocale
|
||
}
|
||
})
|