# 1. 安装vue-i18n
cnpm install [email protected] --save-dev
默认安装是9点多版本,发现启动后报错,就找到了这个版本安装的
# 2. 按需引入elementUi,这个可以参考官网
## 新建一个elementUI.js文件
```js
import Vue from "vue";
import {
Select,
Option,
Pagination,
Radio,
RadioGroup,
Input,
Checkbox,
CheckboxGroup,
Upload,
DatePicker,
Dialog,
Popover,
Button,
Loading,
} from "element-ui"; // 引入 element-ui
Vue.use(Select);
Vue.use(Option);
Vue.use(Pagination);
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(Input);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Upload);
Vue.use(DatePicker);
Vue.use(Dialog);
Vue.use(Popover);
Vue.use(Button);
Vue.use(Loading.directive);
```
# 3.引入VueI18n
## 修改main.js文件
可以全引elementUI,我是按需引入,全引的参考注释部分
```js
// import ElementUI from "element-ui";
import "./assets/js/elementUI";
import "element-ui/lib/theme-chalk/index.css";
// import locale from "element-ui/lib/locale/lang/en";
// Vue.use(ElementUI, { locale });
import VueI18n from "vue-i18n";
import enLocale from "element-ui/lib/locale/lang/en"; //引入Element UI的英文包
import zhLocale from "element-ui/lib/locale/lang/zh-CN"; //引入Element UI的中文包
Vue.use(VueI18n); //通过插件的形式挂载
// Vue.use(ElementUI, {
// i18n: (key, value) => i18n.t(key, value),
// });
/*---------使用语言包-----------*/
const i18n = new VueI18n({
locale: "zh", // 语言标识
messages: {
zh: Object.assign(require("@/lang/zh"), zhLocale), //这里需要注意一下,是如何导入多个语言包的
en: Object.assign(require("@/lang/en"), enLocale),
},
});
new Vue({
i18n,
router,
store,
render: (h) => h(App),
}).$mount("#app");
```
### 在src里面新建lang文件夹,lang文件里面新建en.js和zh.js
en.js
```js
module.exports = {
message: {
login: "Login",
Username: "Username",
Password: "Password",
Captcha: "Captcha",
Language: "Language",
zh: "Chinese",
en: "English",
},
country: {
china: "China",
america: "America",
britain: "Britain",
},
};
```
zh.js
```js
module.exports = {
message: {
login: "登录",
Username: "用户名",
Password: "密码",
Captcha: "验证码",
Language: "语言",
zh: "中文",
en: "英文",
},
country: {
china: "中国",
america: "美国",
britain: "英国",
},
};
```
# 4.使用
```js
item.label
}}
- {{ $t(item.name) }}
import utils from "@/assets/js/utils"; // 引入工具函数
import ossClient from "@/assets/js/aliyun.oss.client";
export default {
data() {
return {
language: 0,
lang: [
{
label: this.$t("message.zh"), //模板语法的一种
value: 0,
},
{
label: this.$t("message.en"),
value: 1,
},
],
country: [
{
id: 1,
name: "country.china",
},
{
id: 2,
name: "country.america",
},
],
};
},
mounted() {
if (this.$store.state.token) {
this.token = this.$store.state.token;
}
this.$i18n.locale === "zh" ? (this.language = 0) : (this.language = 1); //数据加载时判断当前属于哪种语言,为其单选按钮赋值
},
watch: {
//侦听器
language: function (val) {
//侦听单选按钮的变化,从而进行切换语言
val === 0 ? (this.$i18n.locale = "zh") : (this.$i18n.locale = "en");
this.lang = [
{
label: this.$t("message.zh"), //如果不使用Vue.set,也可以使用更新数据的方法
value: 0,
},
{
label: this.$t("message.en"),
value: 1,
},
];
},
},
methods: {
addBritain() {
this.country.push({
id: 3,
name: "country.britain",
});
},
},
};
```