Vue I18n 是 Vue.js 的国际化插件。它可以轻松地将一些本地化功能集成到你的 Vue.js 应用程序中。如何使用i18n做语言切换呢?首先,需要搭建一个vue项目。https://www.cnblogs.com/rogerwu/p/7744476.html
具体搭建方法请参考:Window下基于vue cli4 创建一个vue项目。
一、安装方法
此处只演示 npm
npm install vue-i18n
二、项目结构
三、集成方法
1.在src目录下,新建一个文件夹i18n,然后在i18n目录下,新建一个index.js,内容如下:
import { createI18n } from 'vue-i18n' //按需加载,引入vue-i18n组件
const i18n = createI18n({
legacy: false, // 使用CompotitionAPI必须添加这条.
locale: 'zh', // 首选语言
fallbackLocale: 'zh', // 备选语言
globalInjection: true, // 加上这一句
// 将其设为true,则所有前缀为$的属性和方法(只是vue-i18n所携带的)将被注入到所有vue组件中.
// 即在所有组件中都可以使用 $i18n $t $rt $d $n $tm
//messages,
//方法一:直接定义messages
/* messages: {
"zh": {
hello: "你好,世界!",
home: {
title: "欢迎来到地球!",
},
},
"en": {
hello: "hello, world!",
home: {
title: "Welcome to the Earth!",
},
},
}, */
//方法二:引用外部配置文件
messages: {
"zh": require(`@/i18n/lang/zh.json`),
"en": require(`@/i18n/lang/en.json`)
}
});
export default i18n
messages的配置方法有三种
- 在createI18n时使用,直接定义messages内容
- 在createI18n时使用,引用外部文件,并在外部配置相应内容
zh.json
{
"hello": "你好,世界!!",
"home": {
"title": "欢迎来到地球!!"
}
}
en.json
{
"hello": "hello, world!!",
"home": {
"title": "Welcome to the Earth!!"
}
}
- 在使用的界面,局部设置messages
2.在main.js下引用i18n下的文件
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
//引入i18n
import i18n from "./i18n";
const app = createApp(App);
app.use(store);
app.use(router);
app.use(i18n);//使用i18n
app.mount("#app");
3.在App.vue界面使用i18n,实现多语言切换
<template>
<div class="hello-world">
<!-- 语言切换 -->
<span>语种:</span>
<select v-model="locale" @change="changeLang($event)">
<option value="zh">简体中文</option>
<option value="en">English</option>
</select>
<!-- t是从执行useI18n函数解构得到函数, hello是自己定义的变量 -->
<p>{{ t("hello") }}</p>
<p>{{ t("home.title") }}</p>
<p>{{ hello }}</p>
</div>
</template>
<script>
import {computed,reactive,toRefs} from "vue";//导入vue需要使用的组件
import {useI18n} from "vue-i18n"; //导入并使用
export default {
setup() {
const state = reactive({
locale : 'zh'
})
const {t, locale} = useI18n({
// 方法三:传入messages对象, 里面分别是需要被安排的文字. "zh" - 中文, "en" - 英文, 两个对象的key必须完全一致.
messages: {
"zh": {
hello: "你好,世界!!!",
home: {
title: "欢迎来到地球!!!",
},
},
"en": {
hello: "hello, world!!!",
home: {
title: "Welcome to the Earth!!!",
},
},
},
});
// t是一个函数,能在mustache(模板语法)中使用,当然也能在setup函数任何地方使用
const hello = computed(() => t("hello"));
//切换语言
const changeLang = (event) => {
locale.value = event.target.value;
}
return {
...toRefs(state),
t,
hello,
changeLang
};
},
};
</script>
<style scoped>
</style>