雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

uniapp 国际化开发指南【多语言】

2024-09-30 17

1. uniapp 的国际化

2. VueI18n 多语言使用

1. uniapp 的国际化


zh-Hans 简体中文 zh-Hant 繁体中文

国际化 (Internationalization,简称 i18n):指软件开发具备支持多种语言的地区功能

i18n 简称的来源是单词 Internationalization 的首末字符 i 和 n,18 为中间的字符数量

uniapp 的国际化开发指南文档 : https://uniapp.dcloud.net.cn/tutorial/i18n.html

2. VueI18n 多语言使用


一、创建国际化 json 文件

├── locale│   ├── index.js│   ├── en.json│   ├── zh-Hans.json│   └── zh-Hant.json

语言文件示例 (zh-Hans.json) :

{    "app.name": "天乐商城",    "index.title": "首页",}

合并导出国际化 json 文件 (index.js) :

import en from './en.json';import zhHans from './zh-Hans.json';export default { 'zh-Hans': zhHans, en }

二、main.js 引入并初始化 VueI18n

// 导入国际化 json 文件import messages from '@/locale/index'const i18nConfig = { locale: uni.getLocale(), messages }// Vue 安装 VueI18nimport VueI18n from 'vue-i18n'Vue.use(VueI18n)const i18n = new VueI18n(i18nConfig)// 挂载到 Vue 实例const app = new Vue({    ...App,    i18n})

三、使用多语言

页面模板中使用 $t 获取,并传递国际化 json 文件中定义的 key

<view>{{ $t('index.title') }}</view>

js 中使用 this.$t(),注意: this 指向的是 vue 实例

this.$t('index.title')

pages.json 中使用

{    "pages": [{        "path": "pages/index/index",        "style": {            // 使用 %% 占位            "navigationBarTitleText": "%index.title%"        }    }],    "tabBar": {        "list": [{            "pagePath": "pages/index/index",            // 使用 %% 占位            "text": "%index.home%"        }]    }}

四、切换语言

uni.setLocale() 在 App 中会重启应用

uni.setLocale('en')this.$i18n.locale = 'en'
更新于:18天前
赞一波!

文章评论

评论问答