npm install vue-i18n
yarn add vue-i18n
import Vue from 'vue';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
const messages = {
en: {
welcome: 'Welcome to our application'
},
fr: {
welcome: 'Bienvenue dans notre application'
}
};
const i18n = new VueI18n({
locale: 'en', // 设置默认语言
messages
});
new Vue({
i18n,
render: h => h(App)
}).$mount('#app');
<template>
<div>
<p>{{ $t('welcome') }}</p>
<button @click="changeLanguage('fr')">Change to French</button>
</div>
</template>
<script>
export default {
methods: {
changeLanguage(lang) {
this.$i18n.locale = lang;
}
}
};
</script>
new VueI18n(options)
:初始化 i18n 实例,options
包含 locale
、messages
等配置。key
:翻译字符串的键。this.$i18n.locale = 'fr'
:切换当前语言。locale
:语言代码。messages
:翻译内容对象。locale
:语言代码。可以通过异步加载翻译文件来优化性能,尤其适用于大型应用:
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import axios from 'axios';
Vue.use(VueI18n);
const i18n = new VueI18n({
locale: 'en',
messages: {}
});
function loadLanguageAsync(lang) {
if (!i18n.getLocaleMessage(lang)) {
return axios.get(`/locales/${lang}.json`).then(response => {
i18n.setLocaleMessage(lang, response.data);
i18n.locale = lang;
});
}
i18n.locale = lang;
return Promise.resolve();
}
export default i18n;
vue-i18n 提供了内置的日期和数字格式化功能:
const i18n = new VueI18n({
locale: 'en',
messages,
dateTimeFormats: {
en: {
short: {
year: 'numeric', month: 'short', day: 'numeric'
}
},
fr: {
short: {
year: 'numeric', month: 'short', day: 'numeric'
}
}
},
numberFormats: {
en: {
currency: {
style: 'currency', currency: 'USD'
}
},
fr: {
currency: {
style: 'currency', currency: 'EUR'
}
}
}
});
在组件中使用:
<template>
<div>
<p>{{ $d(new Date(), 'short') }}</p>
<p>{{ $n(123456, 'currency') }}</p>
</div>
</template>