locale.ts 1.4 KB
Newer Older
V
Vben 已提交
1
import type { LocaleSetting, LocaleType } from '/#/config';
2

V
Vben 已提交
3 4
import { defineStore } from 'pinia';
import { store } from '/@/store';
5 6 7 8 9 10 11

import { LOCALE_KEY } from '/@/enums/cacheEnum';
import { createLocalStorage } from '/@/utils/cache';
import { localeSetting } from '/@/settings/localeSetting';

const ls = createLocalStorage();

V
Vben 已提交
12
const lsLocaleSetting = (ls.get(LOCALE_KEY) || localeSetting) as LocaleSetting;
13

V
Vben 已提交
14 15 16
interface LocaleState {
  localInfo: LocaleSetting;
}
17

V
Vben 已提交
18 19 20 21 22 23
export const useLocaleStore = defineStore({
  id: 'app-locale',
  state: (): LocaleState => ({
    localInfo: lsLocaleSetting,
  }),
  getters: {
24 25
    getShowPicker(state): boolean {
      return !!state.localInfo?.showPicker;
V
Vben 已提交
26
    },
27 28
    getLocale(state): LocaleType {
      return state.localInfo?.locale ?? 'zh_CN';
V
Vben 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
    },
  },
  actions: {
    /**
     * Set up multilingual information and cache
     * @param info multilingual info
     */
    setLocaleInfo(info: Partial<LocaleSetting>) {
      this.localInfo = { ...this.localInfo, ...info };
      ls.set(LOCALE_KEY, this.localInfo);
    },
    /**
     * Initialize multilingual information and load the existing configuration from the local cache
     */
    initLocale() {
      this.setLocaleInfo({
        ...localeSetting,
        ...this.localInfo,
      });
    },
  },
});

// Need to be used outside the setup
export function useLocaleStoreWithOut() {
  return useLocaleStore(store);
55
}