https://github.com/kazupon/vue-i18n github地址
1.
npm install vue-i18n
2.main.js中
import VueI18n from 'vue-i18n'
3.加入一个变量 main修改
const numberFormats = { 'en-US': { currency: { style: 'currency', currency: 'USD' } }, 'ja-JP': { currency: { style: 'currency', currency: 'JPY', currencyDisplay: 'symbol' } } }
4.main 修改(
locale 可以更新语言
)
const i18n = new VueI18n({ locale: 'en-US', // 语言标识
numberFormats
});
5.main修改
new Vue({ router, store, i18n, render: h => h(App) }).$mount('#app')
6.然后在vue里面写
<i >{{ $t("currency.style") }}</i>
就能显示出来了
7.在js里面写
this.$t('currency.style')
就能在js里面输出这个变量值
可以重构
numberFormats
===========================================================================================================================
切换语言
http://kazupon.github.io/vue-i18n/zh/guide/sfc.html#%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95
单文件组件里面
<i18n> { "en": { "hello": "hello world!" }, "ja": { "hello": "こんにちは、世界!" } } </i18n> <template> <div id="app"> <label for="locale">locale</label> <select v-model="locale"> <option>en</option> <option>ja</option> </select> <p>message: {{ $t('hello') }}</p> </div> </template> <script> export default { name: 'app', data () { return { locale: 'en' } }, watch: { locale (val) { this.$i18n.locale = val } } } </script>
http://kazupon.github.io/vue-i18n/zh/guide/locale.html
或者这样,都可以切换
<template> <div class="locale-changer"> <select v-model="$i18n.locale"> <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">{{ lang }}</option> </select> </div> </template> <script> export default { name: 'locale-changer', data () { return { langs: ['ja', 'en'] } } } </script>
========================================================================================================================
延迟加载
一次加载所有翻译文件是过度和不必要的。
http://kazupon.github.io/vue-i18n/zh/guide/lazy-loading.html
在进入router之前先等待获取数据,然后next();
router.beforeEach((to, from, next) => { const lang = to.params.lang loadLanguageAsync(lang).then(() => next()) })