PAI前端骨架中已经集成了包括项目、ElementUI组件、PaiUI组件的国际化语言切换功能。

当前语言记会录在Cookies的locale中。

资源文件定义

默认支持英文、中文两个语言

locales
- en.js
- zh-CN.js

以en.js为例:

import enLocale from 'element-ui/lib/locale/lang/en'

export default {
  common: {
    title: 'LINGYUN',
    english: 'English',
    chinese: '中文',
    welcome: 'Welcome to PAI',
    cancel: 'Cancel',
    relogin: 'ReLogin',
    reloginTips: 'Login has expired, you can stay or login again',
    systemTips: 'System Tips',
    error: 'Error',
    tips: 'Tips',
    noCompany: 'Current account has not joined the company and cannot access!',
  },
  // 根据需要,定义不同的业务单词及其层次语言定义,如:
  module1: {
    label: 'xxx',
    tips: 'yyy',
    more: {
      exampleA: 'exp1',
      exampleB: 'exp2'
    }
  },
  // 集成element语言文件
  ...enLocale,
}

显示

在Vue中:

<template>
  <div>
    {{$t('module1.more.exampleA')}}
  </div>
</template>

<script>
    export default {
        // Nuxt标题设置,支持国际化的写法
        head() {
          return {
            title: this.$t('common.welcome'),
          }
        },
        // ...
        mounted () {
            console.log(this.$t('module1.more.exampleB'))
        }
        // ...
    }
</script>

<style>
</style>

在js文件中:

import Cookies from "js-cookie"
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import enLocale from '@/locales/en'
import zhLocale from '@/locales/zh-CN'
// 为了使用一致的API,使用vue-i18n需要use初始化
Vue.use(VueI18n)
// 新建实例
const i18n = new VueI18n({
  fallbackLocale: 'zh-CN',
  messages: {
    en: enLocale,
    'zh-CN': zhLocale,
  },
})

// 每次使用前,需要更新locale(保持修改locale动态生效,vue-i18n的locale配置不支持方法返回)
i18n.locale = Cookies.get('locale') || 'zh-CN'

// 取值显示
console.log(i18n.t('common.reloginTips'))

切换语言

在Vue页面中:

<template>
  <div>
    <button @click="$store.commit('SET_LANG', 'zh-CN')">
      中文
    </button>
    <br/>
    <button @click="$store.commit('SET_LANG', 'en')">
      英文
    </button>
  </div>
</template>

<script>
  export default {
      // ...
      mounted () {
          // 设置为中文
          this.$store.commit('SET_LANG', 'zh-CN')
          // 设置为英文
          this.$store.commit('SET_LANG', 'en')
      }
      // ...
  }
</script>
文档更新时间: 2021-05-13 08:53   作者:姚连洲