参考网站与文章:
https://blog.csdn.net/qq_46490956/article/details/133814009
1.使用npm在uniapp项目根目录下安装vue-i18n
npm install vue-i18n@9.2.2 --save
2.uniapp项目根目录下创建目录locale,用于放置国际化资源json文件
@/locale/zh-Hans.json
{
"index.home":"首页",
"schedule.index":"日程",
"code.index":"二维码",
"message.index":"消息",
"my.index":"我的"
}
@/locale/en.json
{
"index.home":"Home",
"schedule.index":"Schedule",
"code.index":"Code",
"message.index":"Message",
"my.index":"My"
}
3.uniapp项目根目录下创建文件locale/index.js,用于对外暴露资源文件
@/locale/index.js
// 本文件用于对外暴露资源文件
// 引入国际化资源 json 文件
import en from './en.json'
import zhHans from './zh-Hans.json'
// 构建messages资源配置
const messages = {
en,
'zh-Hans': zhHans
}
export default messages
4.main.js引入
// ******************* 国际化i18n配置 start *******************
// 引入国际化资源文件
import messages from './locale/index.js'
// 构建国际化资源配置文件
const i18nConfig = {
locale: uni.getLocale() || 'zh-Hans', // 获取已设置的语言(默认简体中文)
messages
}
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n(i18nConfig)
// ******************* 国际化i18n配置 end *******************
// 不同版本VUE配置参考如下
// VUE2
// #ifndef VUE3
import Vue from 'vue'
import VueI18n from 'vue-i18n'// v8.x
Vue.use(VueI18n)
const i18n = new VueI18n(i18nConfig)
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
i18n,
...App
})
app.$mount()
// #endif
// VUE3
// #ifdef VUE3
import { createSSRApp } from 'vue'
import { createI18n } from 'vue-i18n'// v9.x
const i18n = createI18n(i18nConfig)
export function createApp() {
const app = createSSRApp(App)
app.use(i18n)
return {
app
}
}
// #endif
5.引入使用
<!-- vue文件中引入国际化资源 -->
<text style="margin-left: 5px">{{ $t('get_start') }}</text>
// pages.json中引入国际化资源,使用%%
{
"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%"
}
]
}
}
//在js或者ts中使用
vue2在js中多语言用的是this.$t('index.home')
vue3中this为undefined,所以用下面的方法
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const test = () => {
console.log(t('index.home'))
}
</script>
Q.E.D.