首先下载依赖包 vue-i18n
npm install vue-i18n -S
创建语言包 en 英文,zh中文
// zh.js
const zh = {
about: "关于",
home: "首页"
};
export default zh;
// en.js
const en = {
about: "About",
home: "Home"
};
export default en;
然后在main.js中导入模块,设置全局变量
// main.js
import VueI18n from "vue-i18n";
import zh from "common/lang/zh";
import en from "common/lang/en";
Vue.use(VueI18n);
const i18n = new VueI18n({
locale: "zh", // 默认使用中文包,如需英文 设置 en
messages: {
zh: zh, // 加载中文包
en: en // 加载英文包
}
});
new Vue({
router,
store,
i18n, //加载模块
render: h => h(App)
}).$mount("#app");
这样就设置完了,下面开始使用
{{$t("home")}} //用 $t("变量名") 代替需要显示的 地方
// 切换中英文
<template>
<h2>{{$t("home")}}--{{$t("about")}}</h2>
<select @change="langChange" :value="this.$i18n.locale">
<option value="zh">中文</option>
<option value="en">English</option>
</select>
</template>
<script>
export default {
methods:{
langChange(e) {
this.$i18n.locale = e.target.value; // 切换语言包
}
}
}
</script>