vue使用i18n实现国际化

  1. 安装
npm install vue-i18n@next
  1. 在src下创建一个名为i18n的文件夹,并按照下图创建需要的文件
    vue使用i18n实现国际化_第1张图片

    • 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
});


  1. 在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) });
  1. 在vue文件中使用
    • 如果在某个页面特有的文本,直接在页面写

{
  "zh-CN": {    
    "DATE": "日期", 
  },
  "en": {
     "DATE": "Date", 
  }
} 

具体如下




{
  "zh-CN": {    
    "DATE": "日期", 
  },
  "en": {
     "DATE": "Date", 
  }
} 

你可能感兴趣的:(vue.js,前端,javascript)