index.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. interface IObject {
  2. [key: string]: any;
  3. }
  4. function deepFrom (obj: any, keys: string[], depth: number): any {
  5. const currentKey = keys[depth];
  6. const hasKey = currentKey in obj;
  7. if (!(obj instanceof Object) && depth < keys.length - 1) {
  8. return null;
  9. }
  10. if (obj instanceof Object && !(currentKey in obj)) {
  11. return null;
  12. }
  13. if (depth === keys.length - 1) {
  14. return obj[currentKey];
  15. }
  16. return deepFrom(obj[currentKey], keys, depth + 1);
  17. }
  18. class LangIntl {
  19. private locales: { [key: string]: any } = {}
  20. private currentLocale: string = 'zh-CN';
  21. private deepGet (keyStr: string) {
  22. const locale = this.locales[this.currentLocale];
  23. if (keyStr in locale) {
  24. const keys = keyStr.split('.');
  25. const value = deepFrom(locale, keys, 0);
  26. if (value === null) {
  27. console.warn('kv不匹配');
  28. return '';
  29. }
  30. return value;
  31. }
  32. console.warn('locale 资源未加载.')
  33. return ''
  34. }
  35. public get (keyStr: string) {
  36. return this.deepGet(keyStr)
  37. }
  38. private initFromBrowser() {
  39. return navigator.language;
  40. }
  41. public init () {
  42. this.currentLocale = this.initFromBrowser();
  43. }
  44. }
  45. function intl () {
  46. }
  47. export default intl;