1. 简单使用
-
安装依赖
$ npm install vue-i18n
-
src下创建lang文件夹以及文件夹下zh.js,en.js和index.js文件
-
zh.js
export default { message: '好好学习 天天向上' };
-
en.js
export default { message: 'Good good study,Day day up' };
-
index.js
import Vue from 'vue'; import VueI18n from 'vue-i18n'; import zh from './zh'; import en from './en'; Vue.use(VueI18n); const messages = { zh, en }; const i18n = new VueI18n({ locale: '', //设置当前所使用的语言 zh or en messages }); export default i18n;
-
-
main.js中导入/lang/index.js
import Vue from 'vue'; import App from './App.vue'; import router from './router'; import store from './store'; import i18n from './lang'; Vue.config.productionTip = false; new Vue({ router, store, i18n, render: h => h(App) }).$mount('#app');
-
使用
$t('message')
2. 结合element-ui i18n使用
- 添加element-ui依赖
$ vue add element-ui // 记得要引入i18n相关模块
- 在lang/index.js中,添加element-ui内置lang
import elementEnLocale from 'element-ui/lib/locale/lang/en'; // element-ui lang
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN';// element-ui lang
//省略其他代码
const messages = {
en: {
...enLocale,
...elementEnLocale
},
zh: {
...zhLocale,
...elementZhLocale
}
};
//省略其他代码
- 在main.js中,对element-ui组件初始化
Vue.use(Element, {
i18n: (key, value) => i18n.t(key, value)
});
3. 在项目中封装
-
vuex中添加对lang的设置
-
index.js
const state = { language: '', }; const getters = { language: state => state.language, } const mutations = { SET_LANGUAGE: (state, language) => { state.language = language; }, } const actions = { setLanguage({ commit }, language) { commit('SET_LANGUAGE', language); }, }; export default { namespaced: true, state, mutations, actions };
-
-
lang/index.js中添加getLanguage()方法,处理messages中locale的值
export function getLanguage() {
//获取设置的language
const chooseLanguage = store.getters.language;
if (chooseLanguage) {
return chooseLanguage;
}
//如果没有设置language 读取本地的language
const language = (navigator.language || navigator.browserLanguage).toLowerCase();
const locales = Object.keys(messages);
for (const locale of locales) {
if (language.indexOf(locale) > -1) {
return locale;
}
}
return 'en';
}
-
在vue中封装组件langSelect进行使用
<template> <el-dropdown trigger="click" class="international" @command="handleSetLanguage"> <div> <svg-icon class-name="international-icon" icon-class="language" /> </div> <el-dropdown-menu slot="dropdown"> <el-dropdown-item :disabled="language==='zh'" command="zh"> 中文 </el-dropdown-item> <el-dropdown-item :disabled="language==='en'" command="en"> English </el-dropdown-item> </el-dropdown-menu> </el-dropdown> </template> <script> export default { computed: { language() { return this.$store.getters.language; } }, methods: { handleSetLanguage(lang) { this.$i18n.locale = lang; this.$store.dispatch('setLanguage', lang); } } }; </script>