美文网首页
组件库国际化

组件库国际化

作者: 行走的蛋白质 | 来源:发表于2020-12-24 21:42 被阅读0次
    • locale.js
    import { $isNullOrEmpty } from '../utils/common';
    
    let lang = 'zh';
    /* let languageData = {
      zh: {},
      en: {}
    };
    const requireAll = (context, type) => context.keys().forEach(path => {
      let name = path.replace(/\.\/|\.js/g, '');
      languageData[type][name] = context(path).default;
    });
    requireAll(require.context('./zh', true, /\.js$/), 'zh');
    requireAll(require.context('./en', true, /\.js$/), 'en'); */
    
    let i18nHandler = function() {
      const vuei18n = Object.getPrototypeOf(this).$t;
      if (typeof vuei18n === 'function') {
        return vuei18n.apply(this, arguments);
      }
    };
    
    export const t = function(path, languageData) {
      /* let value = i18nHandler.apply(this, arguments);
      if (!$isNullOrEmpty(value) && typeof value === 'string' && value !== path) {
        return value;
      } */
      const array = path.split('.');
      let currentData = languageData[lang];
    
      for (let i = 0, j = array.length; i < j; i++) {
        const property = array[i];
        value = currentData[property];
        if (i === j - 1) return value;
        if (!value) return '';
        currentData = value;
      }
      return '';
    };
    
    export const use = function(currentLang) {
      lang = currentLang || lang;
    };
    
    export const i18n = function(fn) {
      i18nHandler = fn || i18nHandler;
    };
    
    export default { use, t, i18n };
    
    • mixin
    import { t, use } from '../locale';
    
    export default {
      beforeCreate() {
        // i18n 初始化
        use(this.$i18n.locale);
      },
      methods: {
        t(...args) {
          return t.apply(this, args);
        }
      }
    };
    

    相关文章

      网友评论

          本文标题:组件库国际化

          本文链接:https://www.haomeiwen.com/subject/oyjvnktx.html