Skip to content

多语言 ​

H5安卓苹果鸿蒙微信小程序其它小程序
√√√√√-

安装 ​

终端在项目根目录下执行命令安装模块

bash
fc-uniapp-x i i18n

项目使用 vue-i18n。当前语言由 FC.useFcSystemStore().language 统一管理,会写入本地,重启后自动恢复。框架安装时已挂载 i18n,业务页不要再调用 createI18n() 或 app.use()。

1. 配置语言文件 ​

业务文案放在 modules/i18n,各语言文件使用相同的 key:

text
modules/i18n/
├── en.json
├── zh-Hans.json
├── zh-Hant.json
└── index.ts
json
{
  "title": "标题"
}

在 modules/i18n/index.ts 注册:

ts
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'

export const localMessages = {
  en,
  'zh-Hans': zhHans,
  'zh-Hant': zhHant
}

新增语言时,同时新增 JSON 文件并加入 localMessages。未命中 key 时回退到 zh-Hans。

2. 页面中翻译 ​

统一用 FC.i18n.t(key)。模板里建议包一层短方法:

vue
<template>
  <view>
    <text>{{ t('title') }}</text>
  </view>
</template>

<script setup lang="ts">
const t = (key : string) : string => FC.i18n.t(key)
</script>

不要在页面里使用 useI18n()。Android 蒸汽模式下它容易拿不到组件上下文,应走全局实例。

3. 切换语言 ​

改 language 即可,i18n 会跟着切换并持久化:

ts
const fcSystemStore = FC.useFcSystemStore()

fcSystemStore.language = 'zh-Hans' // 简体中文
fcSystemStore.language = 'zh-Hant' // 繁体中文
fcSystemStore.language = 'en'      // 英文
fcSystemStore.language = 'auto'    // 跟随系统

language 为空字符串时也表示跟随系统。

完整示例:

vue
<template>
  <view>
    <text>{{ t('title') }}</text>
    <button @click="changeLocale('auto')">跟随系统</button>
    <button @click="changeLocale('zh-Hans')">中文简体</button>
    <button @click="changeLocale('zh-Hant')">中文繁体</button>
    <button @click="changeLocale('en')">英文</button>
  </view>
</template>

<script setup lang="ts">
const fcSystemStore = FC.useFcSystemStore()
const t = (key : string) : string => FC.i18n.t(key)

const changeLocale = (language : string) => {
  fcSystemStore.language = language
}
</script>

4. 默认行为 ​

  • 默认回退语言:zh-Hans
  • 默认语言设置:auto(跟随系统)
  • 持久化 key:fc-system
  • FC.i18n.t() 在 i18n 尚未初始化时原样返回 key