安装:
1
| npm install vue-i18n --save
|
建立语言资源: src/assets/languages
例如中文和英文文件:
英文文件:
1 2 3 4 5 6 7 8 9
| export default { menu: { home: "home", msg: "this is an about page" }, content: { main: "this is content" } }
|
中文文件:
1 2 3 4 5 6 7 8 9 10
| export default { menu: { home: "首页", msg: "这是一个关于页面" }, content: { main: "这里是内容" } }
|
配置语言资源:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import Vue from 'vue'; import VueI18n from 'vue-i18n'; import elEN from 'element-ui/lib/locale/lang/en' import elZH from 'element-ui/lib/locale/lang/zh-CN' import zh from './zh'; import en from './en';
Vue.use(VueI18n);
export default new VueI18n({ locale: localStorage.getItem('language') || 'zh', messages: { zh: Object.assign(zh, elZH), en: Object.assign(en, elEN), } })
|
入口文件main.js
注册:
1 2 3 4 5 6 7
| import i18n from './assets/languages/index'
Vue.use(ElementUI, { i18n: (key, value) => i18n.t(key, value) });
|
使用:
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
| <template> <div class="index"> <h1>{{ $t('menu.home') }}</h1> <div>{{ $t(msg) }}</div> <div class="tab"> <span @click="tab('zh')">中文</span>| <span @click="tab('en')">英文</span> </div> </div> </template>
<script> export default { name: "Index", data() { return { language: "zh", options: [ { value: "zh", label: "中文", }, { value: "en", label: "英文", }, ], msg: "content.main", } }, methods: { tab(type) { localStorage.setItem("language", type); this.$i18n.locale = type; } } }
</script>
|