主要说下nvue官网并不明确,且如果是对象的国际化就有问题
首先看官网
<script>
import {
initVueI18n
} from '@dcloudio/uni-i18n'
// const messages = {} 此处内容省略,和 vue 全局引入的写法一致
const { t } = initVueI18n(messages)
export default {
data() {
return {
}
}
}
</script>
其实就是
index.js
import langEn from './en'
import zhHans from './zh-Hans'
export default {
'en': langEn,
'zh-Hans': zhHans
};
<script>
import {
initVueI18n
} from '@dcloudio/uni-i18n'
import messages from '@/lang/index.js';
const { t } = initVueI18n(messages)
console.log(t('messages'))
console.log(t('grid.visibleToAll'))//不可以使用对象
</script>
这种弊端是如果是对象就有问题,无法获取,下面使用借助i18n,通过原生链方法来实现
i18n.js
import messages from '@/lang/index.js';
const i18nEnable = false;//自行判断
let currentLang
if (i18nEnable) {
currentLang = uni.getStorageSync('CURRENT_LANG')
} else {
currentLang = "zh-Hans"
}
let i18nConfig = {
locale: currentLang, // set locale
messages // set locale messages
}
// #ifdef VUE2
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n(i18nConfig)
// #endif
// #ifdef VUE3
import {
createI18n
} from 'vue-i18n'
const i18n = createI18n(i18nConfig)
// #endif
export default i18n
<script>
import i18n from '@/lang/i18n.js';
export default {
data() {
return {
$t:'',
}
},
onLoad() {
this.$t = function(key) {
var values = [],
len = arguments.length - 1;
while (len-- > 0) values[len] = arguments[len + 1];
return i18n._t.apply(i18n, [key, i18n.locale, i18n._getMessages(), this].concat(values))
};
console.log(t('grid.visibleToAll'))//可以使用对象
}
}
</script>