UNPKG

@fesjs/fes-design

Version:
42 lines (39 loc) 1.44 kB
import { inject, computed, unref } from 'vue'; import { get, isUndefined, isString } from 'lodash-es'; import { zhCN } from '../locales'; import { CONFIG_PROVIDER_INJECTION_KEY } from './const'; const translate = (path, option, locale) => { const config = get(locale, path, undefined); if (isUndefined(config)) { console.warn('[configProvider] 未找到语言配置项, path:', path, ', locale:', locale); return ''; } if (!isString(config)) { console.warn('[configProvider] 语言配置项仅支持字符串类型, path:', path, ', config:', config); return ''; } return config.replace(/\{(\w+)\}/g, (_, key) => { var _option$key; return `${(_option$key = option === null || option === void 0 ? void 0 : option[key]) !== null && _option$key !== void 0 ? _option$key : `{${key}}`}`; }); }; const buildTranslator = locale => { return (path, option) => { return translate(path, option, unref(locale)); }; }; const useLocale = () => { const providerConfig = inject(CONFIG_PROVIDER_INJECTION_KEY, {}); const localeRef = computed(() => { var _providerConfig$local; return ((_providerConfig$local = providerConfig.locale) === null || _providerConfig$local === void 0 ? void 0 : _providerConfig$local.value) || zhCN; }); return { lang: computed(() => { return localeRef.value.name; }), locale: localeRef, t: buildTranslator(localeRef) }; }; export { useLocale };