我的项目是直接在HBuilderX 创建的,所以需要使用npm init -y 初始化package.json文件
npm init -y
文件如下
image.png
安装vue-i18n 命令如下
npm i vue-i18n
新建一个i18n文件夹,在文件夹内创建i18n.js 和 langs 文件夹,在langs文件夹内创建zh-CN和en js文件。文件内容分别如下:
i18n/i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import zhCN from './langs/zh-CN'
import en from './langs/en'
Vue.use(VueI18n)
const messages = {
en,
zhCN
}
const i18n = new VueI18n({
locale: 'zhCN', //默认中文,也可根据系统语言动态设置
messages
})
export default i18n
i18n/langs/en.js
module.exports = {
tabBar:{
index0:'Inquires',
index1:'Orders',
index2:'Messages',
index3:'me',
},
message: {
loginSuccess:'login success',
},
}
i18n/langs/zhCN.js
module.exports = {
tabBar:{
index0:'查询',
index1:'订单',
index2:'消息',
index3:'我的',
},
message: {
loginSuccess:'登录成功',
},
}
文件结构如下
image.png
在main.js中引入i18n,代码如下
import Vue from 'vue'
import App from './App'
import i18n from './i18n/i18n'
import store from './store/index'
import http from './utils/https'
Vue.config.productionTip = false
Vue.prototype.request = http
Vue.prototype.$store = store
Vue.prototype._i18n = i18n
App.mpType = 'app'
const app = new Vue({
store,
i18n,
...App
})
app.$mount()
直接在页面中使用 {{$t("message.loginSuccess")}}
效果:
image.png
切换效果,代码如下:
toggleLang() {
if (this.$i18n.locale == 'en') {
this.$i18n.locale = 'zhCN'
} else {
this.$i18n.locale = 'en'
}
}
image.png
image.png
tabBar 语言切换用
uni.setTabBarItem({
index: 1,
text: that.$t('tabBar.index1')
});