- 安装
npm install vue-i18n@next
-
在src下创建一个名为i18n的文件夹,并按照下图创建需要的文件
- i18n/locales/en.json
{"common": {"BUTTON_OK": "OK","BUTTON_CANCEL": "Cancel","BUTTON_SUBMIT": "Submit","BUTTON_SEARCH": "Search","BUTTON_RESET": "Reset"},"home": {"TODAY": "Today","THIS_WEEK": "This Week","THIS_MONTH": "This Month","DEVICE_UNIT": "Unit","LAST_MONTH": "Last Month"}
}
- i18n/locales/zh-CN.json
{"common": {"BUTTON_OK": "确认","BUTTON_CANCEL": "取消","BUTTON_SUBMIT": "提交","BUTTON_SEARCH": "搜索","BUTTON_RESET": "重置"},"home": {"TODAY": "本日","THIS_WEEK": "本周","THIS_MONTH": "本月","DEVICE_UNIT": "台","LAST_MONTH": "上月"}
}
- i18n/index.js
import Vue from "vue";
import VueI18n from "vue-i18n";Vue.use(VueI18n);function loadLocaleMessages() {const locales = require.context("./locales",true,/[A-Za-z0-9-_,\s]+\.json$/i);const messages = {};locales.keys().forEach(key => {const matched = key.match(/([A-Za-z0-9-_]+)\./i);if (matched && matched.length > 1) {const locale = matched[1];messages[locale] = {...locales(key),...require(`element-ui/lib/locale/lang/${locale}`)};}});return messages;
}export default new VueI18n({locale: "zh-CN",fallbackLocale: "zh-CN",messages: loadLocaleMessages(),silentTranslationWarn: true
});
- 在main.js引入
import Vue from 'vue'
import Element from 'element-ui'
import VueI18n from 'vue-i18n'
Vue.use(ElementUI, { i18n: (key, value) => i18n.t(key, value) });
- 在vue文件中使用
- 如果在某个页面特有的文本,直接在页面写
<i18n>
{"zh-CN": { "DATE": "日期", },"en": {"DATE": "Date", }
}
</i18n>
具体如下
<template><div class="box"><div class="modelTitle"><span style="margin-left:16px;color: #ffffff;">{{$t(`DATE`)}}</span><span>{{$t(`common.BUTTON_MORE`)}}</span></div></div>
</template><i18n>
{"zh-CN": { "DATE": "日期", },"en": {"DATE": "Date", }
}
</i18n>