如果你写的app是用uniapp+vue3来搭建的,这篇国际化一定适合你!
问题描述:因为app有海外用户所以需要配置国际化语言满足客户需求。
解决方案: 在uniapp中内置i18n多语言的配置,只要用户能看见的字(包括html页面,js的一些提示代码,tabbar导航和navigationBarTitleText)都要实现国际化,并且可以做到实时切换语言。
安装
如果是创建项目的时候选择的模板是uni-ui项目,则不需要npm vue-i18n。
npm install vue-i18n --save
下面开始i18n的配置,参考网址:uni-app官网
文件目录:
1.配置语言包
代码配置
为了方便把多语言的配置代码写在了locale/index.ts里面,之后在mian.js中引入
import {
createI18n
} from 'vue-i18n'
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'
const messages = {
en,
'zh-Hans': zhHans,
'zh-Hant': zhHant
}
const i18n = createI18n({
locale: uni.getLocale() || 'zh-Hant', // 获取已设置的语言,如果没有默认繁体
messages
})
export default i18n
在main.js中引入(因为项目是用的vue3,当前只配置vue3)
import App from './App'
import i18n from '@/locale/index'
// vue2
// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// vue3
// #ifdef VUE3
import {
createSSRApp
} from 'vue'
export function createApp() {
const app = createSSRApp(App)
app.use(i18n)
return {
app
}
}
// #endif
在html页面使用
$t是i18n自带的全局配置的方法,可以在html中直接使用
<view class="title">{{$t('index.hello')}}</view>
在js或者ts中使用
vue2在js中多语言用的是this.$t(),但是vue3中this为undefined,所以我这里用的是下面的方法
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const test = () => {
console.log(t('index.home'))
}
</script>
在pages.json中使用 %% 占位
{
"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "%index.home%"
}
},
{
"path": "pages/about/about",
"style": {
"navigationBarTitleText": "%index.about%"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
},
"uniIdRouter": {},
"tabBar": {
"list": [
{
"pagePath": "pages/index/index",
"text": "%index.home%"
},
{
"pagePath": "pages/about/about",
"text": "%index.about%"
}
]
}
}
切换多语言
通过uni.setLocale('设置的值')设置语言,可选值包括但不限于: zh-Hans(简体中文)、zh-Hant(繁体中文)、en(英文),详情请参考上面的官网。
需要注意的是: uni.setLocale()方法会重启该应用。