index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import Vue from 'vue';
  2. import znCH from './lang/zn-CH';
  3. let defaultMessages = {};
  4. let merged = false;
  5. const vueI18nHandler = function() {
  6. const vuei18n = Object.getPrototypeOf(this || Vue).$t;
  7. if (typeof vuei18n === 'function' && !!Vue.locale) {
  8. if (!merged) {
  9. merged = true;
  10. Vue.locale(Vue.config.lang, Object.assign(Vue.config.lang === 'zn-CH' ? znCH : {}, Vue.locale(Vue.config.lang) || {}, defaultMessages));
  11. }
  12. return vuei18n.apply(this, arguments);
  13. }
  14. };
  15. function i18n(keysStr, params) {
  16. let value = vueI18nHandler.apply(this, arguments);
  17. if (value !== null && value !== undefined) return value;
  18. let message = Object.assign({}, Vue.config.lang === 'zn-CH' ? znCH : {}, defaultMessages);
  19. let keys = (keysStr && keysStr.split('.')) || [];
  20. let result = null;
  21. if (keys.length) {
  22. for (let i = 0; i < keys.length; i++) {
  23. let key = keys[i];
  24. if (key && message[key]) {
  25. message = message[key];
  26. result = message;
  27. } else {
  28. result = null;
  29. break;
  30. }
  31. }
  32. }
  33. return simpleTemplate(result, params);
  34. }
  35. function locale(lang, messages) {
  36. if (typeof lang === 'object') {
  37. messages = lang;
  38. lang = Vue.config.lang;
  39. }
  40. Vue.config.lang = lang;
  41. Object.assign(defaultMessages, messages);
  42. }
  43. function getArgType(arg) {
  44. return Object.prototype.toString
  45. .call(arg)
  46. .toLowerCase()
  47. .match(/\s(\w+)/)[1];
  48. }
  49. function simpleTemplate(templ, conf) {
  50. let pars = templ && templ.match(/{.+?}/g);
  51. if (pars && conf) {
  52. pars = pars.map(p => p.replace(/\{\s*(\w+|\d+).*?\}/, '$1'));
  53. pars.forEach((c, i) => {
  54. let reg = new RegExp('{\\s*' + c + '\\s*(?:=\\s*(\\S*?))?\\s*?}', 'g');
  55. templ = templ.replace(reg, (a, b) => {
  56. return getArgType(conf[c]) == 'function' ? conf[c]() : conf[c] !== undefined ? conf[c] : b ? b : a;
  57. });
  58. });
  59. }
  60. return templ;
  61. }
  62. export { i18n, locale };