说明
- 适合 vue2.0版本的官方链接如下:
Vue I18nVue I18n 是 Vue.js 的国际化插件https://kazupon.github.io/vue-i18n/zh/
- 适合vue3.0 版本的官方链接如下(目前该文档只有英文和日语,中文翻译需要借助浏览器-2021-12-11 08:53):
Vue I18nhttps://vue-i18n.intlify.dev/
本文以 vue3.0 的使用为主,以 “中文” 和 “英文” 做演示
安装
npm install vue-i18n@next
在 src 文件夹下创建 language 文件夹,然后新建如下文件:
src/language/index.js:对外暴露的主要文件
import { createI18n } from "vue-i18n"
import zh from "./zh"
import en from "./en"
// 默认语言 -
const default_lang = "zh"
const i18n = createI18n({
locale: default_lang,
zh,
en
})
export default i18n //对外暴露 i18n, 在 main.js 中挂载
src/language/zh.js:中文 - 语言文件
module.exports = {
index:{
hello:"你好,世界"
}
}
src/language/en.js:英文 - 语言文件
module.exports = {
index:{
hello:"hello world"
}
}
在 main.js 中挂载
import { createApp } from "vue";
import App from "./App.vue";
import i18n from "./language";
const app = createApp(App)
app.use(i18n).mount("#app");
页面中使用
<template>
<div class="home">
<div>{{ t("index.hello") }}</div>
</div>
</template>
<script>
import { useI18n } from "vue-i18n";
export default {
name: "Home",
setup() {
const { t } = useI18n();
return {
t,
};
},
};
</script>
----------------------------以上是静态使用---------------------
接下来完成语言的动态切换,具体看注释
<template>
<div class="home">
<!-- 新增 a 标签用来循环 语言 -->
<a
v-for="item in lang_menu"
:key="item.id"
@click="changeLang(item)"
:class="{ active: curren_lang === item.name }"
>{{ item.name }}
</a>
<!-- 展示当前选中的语言 -->
<h1>{{ tran_txt.hello }}</h1>
</div>
</template>
<script>
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { getCurrentInstance } from "@vue/runtime-core";
export default {
name: "Home",
setup() {
const { t } = useI18n();
let { ctx } = getCurrentInstance();
// 定义 需要循环的语言
const lang_menu = ref([
{ name: "中文", id: "zh" },
{ name: "英文", id: "en" },
]);
// 默认展示 的语言
const curren_lang = ref("英文");
// 展示 语言内容 的详情
const tran_txt = computed(() => {
return {
hello: t("index.hello"),
};
});
// 切换语言
const changeLang = (item) => {
curren_lang.value = item.name;
ctx.$i18n.locale = item.id; // ---这句话是重点,会动态改变 src/language/index.js 中的语种
};
return {
t,
tran_txt,
curren_lang,
lang_menu,
changeLang,
};
},
};
</script>
结语:
具体代码我会更新到公众号上,关注后回复关键词“vue3切换语言”获取。
---------------公众号放在下面啦,欢迎多多关注呀----------