Skip to content

处理配置文件中 i18n 不更新

思路

拦截对象 key,针对 key 的 get 方法进行国际化翻译

实现

js
const isArray = (data) =>
  Object.prototype.toString.call(data) === '[object Array]'
const isObject = (data) =>
  Object.prototype.toString.call(data) === '[object Object]'

export class IdentificationI18n {
  constructor(key) {
    this.key = key
  }
}

const i18nKey = '_i18n_'
export const genI18nInnerKey = (key) => i18nKey + key

export function proxy4I18n(obj) {
  for (const k in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, k)) {
      if (isObject(obj[k]) && !(obj[k] instanceof IdentificationI18n)) {
        // 若为对象则递归
        proxy4I18n(obj[k])
      } else if (isArray(obj[k])) {
        // 若为数组则遍历、递归
        obj[k].forEach((item) => {
          proxy4I18n(item)
        })
      } else {
        if (obj[k] instanceof IdentificationI18n) {
          const copyObj = JSON.parse(JSON.stringify(obj))
          // 对指定对象key进行get拦截
          Object.defineProperty(obj, k, {
            get() {
              const key = copyObj[k].key
              // 可选 在原对象上挂载 i18n key 备用
              Object.defineProperty(obj, i18nKey + k, {
                enumerable: false,
                value: key,
              })
              // 进行国际化翻译
              return $t(key)
            },
          })
        }
      }
    }
  }
  return obj
}

使用

js
// config.js 
// 该配置对象则被拦截,访问时调用get方法
export default proxy4I18n({
  status: {
    0: new IdentificationI18n('新建'),
    1: new IdentificationI18n('编辑'),
    2: new IdentificationI18n('取消'),
  },
})

Released under the MIT License.