这两天手头的工作是给一个商城我的项目增加多语言。这个商城宏大且简单,是用uniapp+uview ui实现的。商城类的我的项目要增加多语言,不可避免要做大量的文本替换的工作,这么庞杂的一个我的项目怎么能力高效的实现多语言国际化是这篇文章次要要写的货色。
引入vue-i18n
vue-i18n是一个vue插件,次要作用就是让我的项目反对国际化多语言,首先咱们在我的项目引入这个插件:
cnpm vue-i18n
yarn install
main.js
import VueI18n from 'vue-i18n'
增加lang语言文件夹
新建zh-cn.json 和 ug.json
封装i18n不便咱们应用
新建lang/index.js
import Vue from 'vue'import VueI18n from 'vue-i18n'Vue.use(VueI18n);const i18n = new VueI18n({ locale:'zh', messages:{ 'zh':require('@/lang/zh-cn.json'), 'en':require('@/lang/ug.json'), }});if (uni.getStorageSync('locale')) { i18n.locale = uni.getStorageSync('locale')} else { i18n.locale = 'zh-cn'}Vue.prototype._i18n = i18n;export default i18n
vue中应用
mounted() { if (uni.getStorageSync('locale')) { this.$i18n.locale = uni.getStorageSync('locale') } else { this.$i18n.locale = 'zh-cn' } this.langobj= this.$t('goods'); },
js中应用
**import i18n from '../../lang/index'**export default { // 手机号 mobile: [{ required: true, message: i18n.t('shopro.qingshurushoujihao'), trigger: ['change', 'blur'] }, { validator: (rule, value, callback) => { return test.mobile(value); }, message: **i18n.t('shopro.shoujihaomageshibuzhengque'),** trigger: ['change', 'blur'] } ],
多语言切换js
参考
https://segmentfault.com/a/11...