thumbnail

【Vue.js】i18n をテンプレート以外から利用する

Vue I18n の設定例

plugins/i18n.js

import Vue from 'vue';
import VueI18n from 'vue-i18n';
import options from './options';

Vue.use(VueI18n);

export default new VueI18n(options);

app.js

import i18n from './plugins/i18n';

new Vue({

    ....

    i18n,
});

テンプレート内で使用する場合は $t を使用すればよい。

{{ $t('messages.hello') }}

Vueファイル以外のJavaScriptファイル内などから使用する場合は new VueI18n したものを import して使用すればよい。

このとき「$」を除いた名前で呼び出す。

import moment from 'moment';
import i18n from './plugins/i18n';

export const date = value => i18n.d(moment(value).toDate(), 'long');
export const number = value => i18n.tc('unit.number', value, { value });
export const price = value => i18n.t('unit.price', { value });

Makefile で 動的にコマンドを変える方法
next article
arrow