项目地址:https://github.com/wanghaijuan/vue-i18n
相关配置
1 2 3 4 5
| vue-cli: 3.11.0 vue: 2.6.10 node: 0.16.3 npm: 6.12.0 ...
|
安装i18n
1 2 3 4 5
| vue add i18n
npm install vue-i18n
|
vue add i18n
没有更改项目文件,直接新建vue项目后添加i18n插件的,修改 HelloWorld.vue
即可:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| <template> <div class="hello"> <h1>{{ $t('message') }}</h1> <div> <select v-model="optionData.selected" @change="switchLang"> <option v-for="(item, keys) in optionData.list" :key="keys">{{ item.name }}</option> </select> </div> </div> </template>
<script> export default { name: 'HelloWorld', data() { return { optionData: { selected: '', list: [ {lang: 'en', name: 'English'}, {lang: 'zh', name: '简体中文'} ] } } }, created: function () { this.initLang(); }, methods : { initLang() { const lang = this.$i18n.locale; const list = [...this.optionData.list]; this.optionData.selected = list.filter(item => item.lang === lang)[0].name; }, switchLang (event) { const val = event.target.value; const list = [...this.optionData.list]; this.optionData.selected = val; this.$i18n.locale = list.filter(item => item.name === val)[0].lang; }, } } </script>
|
npm install vue-i18n
安装号vue-i18n之后,就创建以下文件,目录如下:
1 2 3 4 5 6 7 8 9 10
| // 在 `src` 文件夹下, 创建 locales 文件夹,如下: |- src |-- locales |--- i18n.js |--- langs |---- en.js |---- zh.js |---- index.js |-- App.vue |-- main.js
|
langs
文件下的的配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| export default { "message": "hello i18n !", }
export default { "message": "你好 i18n !", }
import zh from './zh' import en from './en'
export default { zh, en }
|
i18n.js
文件初始化配置:
1 2 3 4 5 6 7 8 9 10 11 12
| import Vue from 'vue' import VueI18n from 'vue-i18n' import messages from './langs'
Vue.use(VueI18n)
const i18n = new VueI18n({ locale: localStorage.lang || 'zh', messages })
export default i18n;
|
main.js
文件配置:
1 2 3 4 5 6 7 8 9 10
| import Vue from 'vue' import App from './App.vue' import i18n from './locales/i18n'
Vue.config.productionTip = false
new Vue({ i18n, render: h => h(App), }).$mount('#app')
|
最后应该可同 HelloWorld.vue
一致即可。
扩展 npm install vue-i18n
也可把·en.js
与 zh.js
修改成 json
文件,那么langs
下的 index.js
文件可忽略。
配置 en.json
与 zh.json
文件:
1 2 3
| { "message": "你好 i18n !" }
|
修改 i18n.js
文件初始化配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
function loadLocaleMessages () { const locales = require.context('./langs', 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 }
Vue.use(VueI18n)
const i18n = new VueI18n({ locale: localStorage.lang || 'zh', messages: loadLocaleMessages() })
export default i18n;
|