1,首先自行安装i18n
2,src 里面新建i18n.js ,默认是英文 ‘en’
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
function loadLocaleMessages() {
const locales = require.context(
'./locales',
true,
/[A-Za-z0-9-_,\s]+\.json$/i
)
const messages = {}
locales.keys().forEach((key) => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i)
if (matched && matched.length > 1) {
const locale = matched[1]
messages[locale] = locales(key)
}
})
return messages
}
export default new VueI18n({
locale: process.env.VUE_APP_I18N_LOCALE || 'en',
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
messages: loadLocaleMessages(),
})
src 目录locales 新建两个翻译文件 cn.json en.json
en.json
{
"nav": {
"nav1":"游戏",
"nav2":"赏金",
"nav3":"NFT",
"nav4":"协会",
"nav5":"交换",
"nav6":"DAO"
}
}
cn.json
{
"nav": {
"nav1":"Play",
"nav2":"Bounty",
"nav3":"NFT",
"nav4":"Guild",
"nav5":"Swap",
"nav6":"DAO"
}
}
computed 调用翻译文件的字段
computed: {
navs() {
var navlist = [{
navitem: this.$t('nav.nav1')
}, {
navitem: this.$t('nav.nav2')
}, {
navitem: this.$t('nav.nav3')
}, {
navitem: this.$t('nav.nav4')
}, {
navitem: this.$t('nav.nav5')
}, {
navitem: this.$t('nav.nav6')
}]
return [...navlist];
}
},
template 里调用
<div class="v-navbar flex-center">
<div v-for="(item,index) in navs" :key="index" class="v-nav-item">{{item.navitem}}</div>
</div>
切换事件自行添加
swLang(e) {
this.langtext = e
if(e == 'English'){
this.$i18n.locale = 'en'
}else{
this.$i18n.locale = 'cn'
}
}