Ste7en
Ste7en
  • 发布:2018-10-17 16:49
  • 更新:2023-11-17 18:40
  • 阅读:45326

uniapp与vue-i18n实现国际化多语言

分类:uni-app

踩了很多坑,终于捣鼓出来了。

main.js

import Vue from 'vue'  
import App from './App'  
import VueI18n from 'vue-i18n'  

Vue.use(VueI18n)  
Vue.config.productuinTip = false  

const i18n = new VueI18n({  
  locale: 'en-US',  
  messages: {  
    'en-US': {  
      index: {  
        invite: 'Invite',  
        game: 'Game'  
      }  
    },  
    'zh-CN': {  
      index: {  
        invite: '邀请',  
        game: '游戏'  
      }  
    }  
  }  
})  

Vue.prototype._i18n = i18n  
App.mpType = 'app'  

const app = new Vue({  
  i18n,  
  ...App  
})  
app.$mount()

uniapp 不支持在取值表达式中直接调方法,因此,$t方法不可用,所以通过计算属性的方式:

index.vue

<template>  
  <view class="uni-content">  
    <text>{{ i18n.invite }}</text>  
    <text>{{ i18n.game }}</text>  
  </view>  
</template>  

<script>  
export default {  
  computed: {  
    i18n () {  
      return this.$t('index')  
    }  
  }  
}  
</script>  

<style>  
</style>

更多国际化参考https://ask.dcloud.net.cn/article/35872

15 关注 分享
Geeker Trust 春秋战国 sonicsunsky 虫雪浓 易齐 今天回复我了吗 9***@qq.com 没得好名字 z***@sina.com 7***@qq.com 冷月i 1***@qq.com 2***@qq.com MonikaCeng

要回复文章请先登录注册

取舍

取舍

emmm 不用 il18 也可以实现,,
2020-11-19 09:06
迪格立之

迪格立之

回复 Ste7en :
谢谢,看过了。t是i18n的方法,去或许那个_i18n的属性的。
2020-11-19 08:50
Ste7en

Ste7en (作者)

回复 迪格立之 :
查看vue-i18n的源码就知道了。i18n实例是定义在vue的原型上的 `_i18n` 属性。所以要加上上面这行代码
2020-11-18 17:30
Ste7en

Ste7en (作者)

回复 3***@qq.com :
后端统一返回的数据结构: { "code": 200, "msg": "success", "data": {... } }
然后在语言包JSON中配置code码:
{
"errmap": {
"200": "success",
"501": "密码错误",
.....
}
}

然后在js中
const res = await axios.get('/login/', { ... });
const code = res.data.code;
const hasMsg = i18n.te(`errmap.${code}`)
if (hasMsg) {
alert(i18n.t(`errmap.${code}`))
}
// ...
2020-11-18 17:27
1***@qq.com

1***@qq.com

回复 3***@qq.com :
根据code码,前端和后端统一,
2020-11-18 11:26
2***@qq.com

2***@qq.com

回复 silianpan888 :
谁先谁后没关系的,楼主的写法没问题
2020-11-05 15:59
3***@qq.com

3***@qq.com

请问下后端接口返回的msg如何做国际化呢?比如后端接口msg返回的是'bk_username_pass_wrong',前端需要国际化渲染出来,当语言是中文时消息提示‘用户名密码错误’,语言为英文时为‘username or password is wrong’
2020-10-12 18:01
3***@qq.com

3***@qq.com

大佬,请问下后端接口返回的msg如何做国际化呢?
2020-10-12 17:29
迪格立之

迪格立之

Vue.prototype._i18n = i18n
上面这个语句的作用是什么?_i18n换个别的名字的话,在调用$t的页面就报“'_t' of undefined”,哪位U友能帮忙解释一下_i18n是怎么和$t关联起来的?
2020-10-01 12:57
zsb

zsb

回复 zsb :
就用这这个方法
2020-09-01 15:52