| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import { defineStore } from 'pinia'
- import { ref } from 'vue'
- import { defaultLocale, localeList } from '../locales'
- import i18n from '../i18n'
- export const useLocaleStore = defineStore('locale', () => {
- // 当前语言
- const currentLocale = ref(defaultLocale)
-
- // 可用语言列表
- const availableLocales = ref(localeList)
-
- // 初始化语言设置
- const initLocale = () => {
- try {
- const storedLocale = uni.getStorageSync('locale')
- if (storedLocale) {
- currentLocale.value = storedLocale
- i18n.global.locale.value = storedLocale
- }
- } catch (e) {
- console.error('Failed to load locale:', e)
- }
- }
-
- // 切换语言
- const setLocale = (locale) => {
- if (!locale || !localeList.find(item => item.value === locale)) {
- console.error('Invalid locale:', locale)
- return false
- }
-
- // 如果语言相同,直接返回,避免不必要的更新
- if (currentLocale.value === locale) {
- return true
- }
-
- try {
- // 批量更新:先更新 store 状态,再更新 i18n,最后持久化
- // 这样可以减少响应式触发次数
- currentLocale.value = locale
- i18n.global.locale.value = locale
-
- // 异步持久化,不阻塞UI
- setTimeout(() => {
- try {
- uni.setStorageSync('locale', locale)
- } catch (e) {
- console.error('Failed to save locale:', e)
- }
- }, 0)
-
- return true
- } catch (e) {
- console.error('Failed to set locale:', e)
- return false
- }
- }
-
- // 切换到下一个语言
- const toggleLocale = () => {
- const currentIndex = localeList.findIndex(item => item.value === currentLocale.value)
- const nextIndex = (currentIndex + 1) % localeList.length
- const nextLocale = localeList[nextIndex].value
- return setLocale(nextLocale)
- }
-
- // 获取当前语言的显示名称
- const getCurrentLocaleName = () => {
- const locale = localeList.find(item => item.value === currentLocale.value)
- return locale ? locale.label : ''
- }
-
- return {
- currentLocale,
- availableLocales,
- initLocale,
- setLocale,
- toggleLocale,
- getCurrentLocaleName
- }
- })
|