element-ui源码--国际化

791 阅读1分钟

1. 定义t函数

export const t = function(path, options) {
      const array = path.split('.');
      let current = lang;
    
      for (let i = 0, j = array.length; i < j; i++) {
        const property = array[i];
        value = current[property];
        if (i === j - 1) return format(value, options);
        if (!value) return '';
        current = value;
      }
      return '';
};

可以把取得如下对象的值 t('el.colorpicker.confirm')

el: {
   colorpicker: {
     confirm: '确定',
     clear: '清空'
   },
   ...
}

2.format(value, options) 用于将字段中的变量${}或{}替换

const RE_NARGS = /(%|)\{([0-9a-zA-Z_]+)\}/g;
  function template(string, ...args) {
    ...
    return string.replace(RE_NARGS, (match, prefix, i, index) => {
      let result;
      if (string[index - 1] === '{' &&
        string[index + match.length] === '}') {
        return i;
      } else {
        result = hasOwn(args, i) ? args[i] : null;
        if (result === null || result === undefined) {
          return '';
        }
        return result;
      }
    });
  }

3.在组件内mixins后就可以使用this.t('el.datepicker.year')调用t函数

mixins: [Locale],

4.注册插件

opts是Vue.use()的时候传的参数,如果使用了vue-i18n,可以在Vue.use()的时候,将locale和i18n传入;我们的项目在引入element的时候,一般形式如下:

    import Vue from 'vue'
    import ElementUI from 'element-ui'
    import locale from 'element-ui/lib/locale/lang/en'
    Vue.use(ElementUI, { locale })   //不可以切换语言const i18n = new VueI18n({
      locale: 'en', // set locale
      messages, // set locale messages
    })
    Vue.use(Element, {
      i18n: (key, value) => i18n.t(key, value)    //可以切换语言
    })

opts包含key i18n或locale,就可以将element-ui里面按照我们所需的语言展示了

const install = function(Vue, opts = {}) {
  locale.use(opts.locale);
  locale.i18n(opts.i18n);
  ...
}
 
export const use = function(l) {
  lang = l || lang;
};
export const i18n = function(fn) {
  i18nHandler = fn || i18nHandler;
};

切换中英文

i18n 中,有以下方法 watchLocale() ,用来监听 locale 的变化。具体操作,看注释即可。

watchLocale () {
    if (!this._sync || !this._root) { return null }
    const target: any = this._vm // vue 实例
    return this._root.$i18n.vm.$watch('locale', (val) => {
      target.$set(target, 'locale', val) 
      target.$forceUpdate() 
    }, { immediate: true })
  }