vue3國際化、vue3實現多語言切換、vue3使用i18n

邢帅杰發表於2024-05-11
來源:https://blog.csdn.net/m0_66532594/article/details/128376057
https://blog.csdn.net/weixin_51220466/article/details/123889240

1.npm i vue-i18n 或 cnpm i vue-i18n
2.建立 il18n
在src目錄下建立 i18n 資料夾,並在下面分別建立三個語言檔案 :
index.js => 主檔案用於匯入 i18n 和相關配置
zh.js => 存放中文內容
en.js => 存放英文內容

index.js 示例:
import { createI18n } from 'vue-i18n';
import ZH from './zh.js';
import EN from './en.js';
const messages = {
zh: { ...ZH },
en: { ...EN },
};

const i18n = createI18n({
legacy: false,
globalInjection: true,
locale: 'zh',
messages
});
export default i18n;

locale屬性用於設定初始語言,值要和 messages 中的屬性 key ,相互對應。

zh.js 示例
export default {
person: {
name:'張三',
hobby:'唱跳,rap,籃球'
},
};

en.js 示例
export default {
person: {
name:'zhangsan',
hobby:'Singing and dancing, rap, basketball'
},
};

3.在main.js 中配置 i18n
import { createApp } from "vue";
import App from "./App.vue";
import i18n from './i18n/index';
const app = createApp(App);
app.use(i18n).mount("#app");

4.使用
4.1如果只是在 html 中使用,不用在匯入任何東西
<template>
<div>
<span> {{ $t("person.name") }} </span>
<span> {{ $t("person.hobby") }} </span>
</div>
</template>
4.2在js 中使用,需要透過匯入 getCurrentInstance 進行獲取
<script setup>
import { getCurrentInstance } from "vue";
const { $t } = getCurrentInstance().proxy;
console.log( $t("person.name") ); //獲取值
</script>

5.修改語言和獲取當前語言
切換語言要匯入vue-i18n 的 locale 屬性,locale 是ref 物件,要修改value
不要修改 i18n/index.js檔案, 匯出的物件屬性
<script setup>
import { useI18n } from 'vue-i18n'
const { locale } = useI18n()
// 切換中文
function changeZh(){ locale.value = 'zh'; };
// 切換英文
function changeEn(){ locale.value = 'en'; };
</script>

相關文章