locale.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { defineStore } from 'pinia'
  2. import { ref } from 'vue'
  3. import { defaultLocale, localeList } from '../locales'
  4. import i18n from '../i18n'
  5. export const useLocaleStore = defineStore('locale', () => {
  6. // 当前语言
  7. const currentLocale = ref(defaultLocale)
  8. // 可用语言列表
  9. const availableLocales = ref(localeList)
  10. // 初始化语言设置
  11. const initLocale = () => {
  12. try {
  13. const storedLocale = uni.getStorageSync('locale')
  14. if (storedLocale) {
  15. currentLocale.value = storedLocale
  16. i18n.global.locale.value = storedLocale
  17. }
  18. } catch (e) {
  19. console.error('Failed to load locale:', e)
  20. }
  21. }
  22. // 切换语言
  23. const setLocale = (locale) => {
  24. if (!locale || !localeList.find(item => item.value === locale)) {
  25. console.error('Invalid locale:', locale)
  26. return false
  27. }
  28. try {
  29. // 更新 i18n 语言
  30. i18n.global.locale.value = locale
  31. // 更新 store 状态
  32. currentLocale.value = locale
  33. // 持久化到本地存储
  34. uni.setStorageSync('locale', locale)
  35. return true
  36. } catch (e) {
  37. console.error('Failed to set locale:', e)
  38. return false
  39. }
  40. }
  41. // 切换到下一个语言
  42. const toggleLocale = () => {
  43. const currentIndex = localeList.findIndex(item => item.value === currentLocale.value)
  44. const nextIndex = (currentIndex + 1) % localeList.length
  45. const nextLocale = localeList[nextIndex].value
  46. return setLocale(nextLocale)
  47. }
  48. // 获取当前语言的显示名称
  49. const getCurrentLocaleName = () => {
  50. const locale = localeList.find(item => item.value === currentLocale.value)
  51. return locale ? locale.label : ''
  52. }
  53. return {
  54. currentLocale,
  55. availableLocales,
  56. initLocale,
  57. setLocale,
  58. toggleLocale,
  59. getCurrentLocaleName
  60. }
  61. })