仅个人兴趣,在学习的项目中使用
只测试过微信小程序和h5
项目环境
vue3 + pinia + vite + js
i18n
使用npm下载i8n
npm install vue-i18n --save
main.js
import App from './App'
// pinia
import store from './stores'
// i18n
import i18nConfig from '@/locale/index.js'
// 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(store)
app.use(i18n)
return {
app
}
}
// #endif
语言包文件
index.js
import en from './en.json'
import ms from './ms.json'
import thTH from './th-TH.json'
import zhHans from './zh-Hans.json'
const messages = {
'zh-Hans': zhHans,
en,
ms, // 马来语
"th-TH": thTH // 泰语
}
const i18nConfig = {
locale: uni.getLocale(),
messages
}
export default i18nConfig;
en.json
{
"App.name": "Kunteng Mall",
"Chinese" : "Chinese",
"cate.title": "Cate",
"detail.title": "details",
"English": "English",
"index.title": "home Page",
"language": "language",
"search.title": "search",
"shopcart.title": "shopping cart",
"mycenter.title": "Personal Center"
}
th-Th.json
{
"App.name": "เดอะมอลล์",
"Chinese" : "ภาษาจีน",
"cate.title": "หมวดหมู่",
"detail.title": "รายละเอียด",
"English": "ภาษาไทย",
"index.title": "หน้าหลัก",
"language": "ภาษา",
"search.title": "ค้นหา",
"shopcart.title": "ตะกร้าสินค้า",
"mycenter.title": "ศูนย์ส่วนบุคคล"
}
json文件的起名,参考了i18n国际语言代码对照表
manifest.json
** 注:此处不更改,点击切换语言不生效**
基础配置-国际化-默认语言-跟随系统或宿主的语言配置(auto)
页面使用
<view class="uni-ellipsis-1">
{{ $t('App.name')}}
</view>
<!--语言切换 -->
<view class="language-box">
<text class="margin-right-20">{{ $t('language') }}: </text>
<uni-data-select
v-model="languageValue"
:localdata="range"
@change="changeLanguage"
></uni-data-select>
</view>
<script>
// 国际化-切换语言
const languageValue = uni.getLocale();
const range = reactive([
{value: 'zh-Hans', text: 'zh-Hans'},
{value: 'en', text: 'en'},
{value: 'ms', text: 'ms'},
{value: 'th-TH', text: 'th-TH'}
])
const intance = getCurrentInstance();
const changeLanguage = (e) => {
intance.ctx.$i18n.locale = e;
}
</script>