实现国际化
安装依赖,限制在 8.0 版本内,最新的 9.0 版本会报错导致页面显示空白(本人已踩坑)
1
| npm install express@8.26.8 --save
|
然后再根目录新建 I18n
文件夹,分别创建 index.js
, config/zh.js
,config/en.js
。目录结构如下

分别往 zh.js
和 en.js
文件中定义一些内容
zh.js
1 2 3
| export default { language: "中文" }
|
en.js
1 2 3
| export default { language: "English" }
|
然后在 index.js
中引入,同时和 elementUI
的国际化做兼容处理
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
| import Vue from 'vue' import VueI18n from 'vue-i18n' import zh from './config/zh' import en from './config/en' import enLocale from 'element-ui/lib/locale/lang/en' import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(VueI18n)
const messages = { 'zh': { ...zh, ...zhLocale }, 'en': { ...en, ...enLocale } }
let locale = localStorage.getItem("locale") || 'zh'
const i18n = new VueI18n({ locale, messages })
export default i18n
|
接着修改 main.js
文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import ElementUI from 'element-ui'; import i18n from './I18n' import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false
Vue.use(ElementUI, { i18n: (key, value) => i18n.t(key, value) })
new Vue({ router, store, i18n, render: h => h(App) }).$mount('#app')
|

之后我们在页面中通过 $t('xxx')
的方式读取国际化中配置的文字
编写 demo
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <template> <div> <div>当前语言:{{ $t('language') }}</div> <el-button type="primary" @click="changeLocale('zh')">切换为中文</el-button> <el-button type="success" @click="changeLocale('en')">切换为英文</el-button> </div> </template> <script> export default { methods:{ changeLocale(locale){ localStorage.setItem("locale",locale) window.location.reload() } } } </script>
|
效果演示
