Vue I18n で翻訳がある時とない時で処理を変える

vue-i18nを使って多言化に対応する際にen.jsonなど言語毎の辞書ファイルを用意することになるかと思いますが中には翻訳漏れで対応できていない箇所等もあるかと思います。
それを画面上で文言等を出力して確認できたらいいなと思い、vue-i18nがデフォルトで与えてくれる$tメソッドをオーバーライドするような形で対応したので備忘録として残しておきます。

翻訳用のプラグインを作って対応する

vue-i18nでは$tメソッドによってロケールに応じたテキストを出力してくれます。
このメソッドを上書きする形でカスタマイズします。

Vue.jsではinstall メソッドを持つオブジェクトを定義してVue.use()メソッドを使用するとプラグインとして機能してくれるのでそれを使います。vue-i18n > src > extend.jsを見るとほぼほぼ流用できそうな記述があったのでそれを利用します。

/* @flow */

export default function extend (Vue: any): void {
  if (!Vue.prototype.hasOwnProperty('$i18n')) {
    // $FlowFixMe
    Object.defineProperty(Vue.prototype, '$i18n', {
      get () { return this._i18n }
    })
  }

  Vue.prototype.$t = function (key: Path, ...values: any): TranslateResult {
    const i18n = this.$i18n
    return i18n._t(key, i18n.locale, i18n._getMessages(), this, ...values)
  }

  Vue.prototype.$tc = function (key: Path, choice?: number, ...values: any): TranslateResult {
    const i18n = this.$i18n
    return i18n._tc(key, i18n.locale, i18n._getMessages(), this, choice, ...values)
  }

  Vue.prototype.$te = function (key: Path, locale?: Locale): boolean {
    const i18n = this.$i18n
    return i18n._te(key, i18n.locale, i18n._getMessages(), locale)
  }

  Vue.prototype.$d = function (value: number | Date, ...args: any): DateTimeFormatResult {
    return this.$i18n.d(value, ...args)
  }

  Vue.prototype.$n = function (value: number, ...args: any): NumberFormatResult {
    return this.$i18n.n(value, ...args)
  }
}

$teメソッドを使ってkeyが存在するか判定する

$teメソッドを使用することで翻訳ファイルに任意のキーが存在するかどうか判定してくれます。

import VueI18n from "vue-i18n";

Vue.use(VueI18n);
Vue.use({
    install(Vue) {
        Vue.prototype.$t = function(key, ...values) {
        const i18n = this.$i18n;

        if (!this.$te(key)) {
            // $te は翻訳があれば true、なければ false
            return (
            i18n._t(key, i18n.locale, i18n._getMessages(), this, ...values) +
            "(辞書登録がありません!)"
            );
        }

        return i18n._t(key, i18n.locale, i18n._getMessages(), this, ...values);
        };
    }
});


コメントを残す

入力エリアすべてが必須項目です。メールアドレスが公開されることはありません。

内容をご確認の上、送信してください。