index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import Format from './format';
  2. import defaultLang from './lang/zh';
  3. import { createApp } from 'vue'
  4. const Vue = createApp({})
  5. const format = Format(Vue);
  6. let lang = defaultLang;
  7. let merged = false;
  8. let i18nHandler = function () {
  9. const vuei18n = Object.getPrototypeOf(this || Vue || {}).$t;
  10. if (typeof vuei18n === 'function' && !!Vue.locale) {
  11. if (!merged) {
  12. merged = true;
  13. Vue.locale(
  14. Vue.config.lang,
  15. Object.assign(lang, Vue.locale(Vue.config.lang) || {}, { clone: true })
  16. );
  17. }
  18. return vuei18n.apply(this, arguments);
  19. }
  20. };
  21. export const t = function (path, options) {
  22. let value = i18nHandler.apply(this, arguments);
  23. if (value !== null && value !== undefined) return value;
  24. const array = path.split('.');
  25. let current = lang;
  26. for (let i = 0, j = array.length; i < j; i++) {
  27. const property = array[i];
  28. value = current[property];
  29. if (i === j - 1) return format(value, options);
  30. if (!value) return '';
  31. current = value;
  32. }
  33. return '';
  34. };
  35. export const use = function (l) {
  36. lang = l || lang;
  37. };
  38. export const i18n = function (fn) {
  39. i18nHandler = fn || i18nHandler;
  40. };
  41. export default { use, t, i18n };