vue使用i18n实现国际化

  1. 安装
npm install vue-i18n@next
  1. 在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
});


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

相关推荐

  1. uniapp 使用vue-i18n实现传入变量国际化

    2024-01-18 21:08:01       47 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-18 21:08:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-18 21:08:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-18 21:08:01       82 阅读
  4. Python语言-面向对象

    2024-01-18 21:08:01       91 阅读

热门阅读

  1. MySQL中WITH AS语句的使用

    2024-01-18 21:08:01       60 阅读
  2. iOS长按时无法保存图片问题解决方案

    2024-01-18 21:08:01       83 阅读
  3. 力扣79. 单词搜索

    2024-01-18 21:08:01       55 阅读