1、下载插件
npm i vue-i18n@8.22.2
2、新建文件夹i18n
3、编写index.js文件
import Vue from "vue";
import VueI18n from "vue-i18n";
import locale from 'element-ui/lib/locale';
// 引入 elementui 的多语言
import enLocale from 'element-ui/lib/locale/lang/en'
import zhCnLocale from 'element-ui/lib/locale/lang/zh-CN'
// 引入自己定义的 I18n 文件
import en from "./lan/en.json";
import zh from "./lan/zh.json";
Vue.use(VueI18n); // 全局挂载
export const i18n = new VueI18n({
locale: localStorage.getItem("lang") || "zh", // 从localStorage中获取 默认英文
messages: {
zh: Object.assign(zh, zhCnLocale), // 中文语言包
en: Object.assign(en, enLocale) // 英文语言包
}
});
locale.i18n((key, value) => i18n.t(key, value));
export default i18n;
4、编写en.json文件和zh.json文件
5、修改main.js文件
import Vue from 'vue'
import Element from 'element-ui'
import './assets/styles/element-variables.scss'
import { i18n } from './i18n/index'
new Vue({
el: '#app',
i18n,
render: h => h(App)
})
6、 页面显示的语法
<!-- 这个按钮方便我们用来切换语言 -->
<template>
<div class="full" @click="changeLangEvent()">
<span class="lan">{{language}}</span>
<h3 class="title">{{ $t('login.WelcomeToLogin') }}</h3>
</div>
</template>
<script>
export default {
data (){
return {
language: localStorage.getItem("lang") ||"en"
}
},
methods:{
changeLangEvent() {
if (this.language == "en") {
this.$i18n.locale = 'zh';
this.$message({
message: "切换为中文!",
type: "success"
});
localStorage.setItem("lang", "zh");
this.language = "zh";
} else if (this.language == "zh") {
this.$i18n.locale = 'en';
this.$message({
message: "Switch to English!",
type: "success"
});
localStorage.setItem("lang", "en");
this.language = "en";
}
},
}
</script>