1、下载vue-i18n:
npm i vue-i18n@next
2、新建三个语言相关文件:
2.1、index.js:
import {
createI18n
} from "vue-i18n";
import zh from "./zh";
import en from "./en";
const i18n = createI18n({
locale: localStorage.getItem('language') || 'zh', // 定义默认语言为中文
messages: {
zh,
en,
},
});
export default i18n;
2.2、en.js:
export default {
language: {
index: "English"
}
}
2.3、zh.js:
export default {
language: {
index: "汉语"
}
}
3、main.js:
import vueI18n from '@/lang/index'
createApp(App).use(vueI18n).mount('#app')
4、多语言使用、多语言切换 -- index.vue:
<template>
<!-- 语言切换 -->
<div>
<div>
<div @click="handEvent(0)">中文</div>
<div @click="handEvent(1)">英文</div>
</div>
<div>
{{ $t("language.index") }}
</div>
</div>
</template>
<script>
export default {
data() {
return {}
},
methods: {
handEvent(type) {
if (type == 0) {
localStorage.setItem("language", "zh")
this.$i18n.locale = "zh" //这个代码负责实时切换语言
} else if (type == 1) {
localStorage.setItem("language", "en")
this.$i18n.locale = "en" //这个代码负责实时切换语言
}
}
}
}
</script>