Vue3组合式API + TS项目中手写国际化插件

发布于:2024-05-04 ⋅ 阅读:(143) ⋅ 点赞:(0)

1. 在项目中创建一个国际化插件的文件i18n.ts

<!-- plugins/i18n.ts -->
export const i18nPlugin = {
    install(app: any, option: any) {
        app.config.globalProperties.$t = (key: string) => {
            return key.split(".").reduce((o, k) => {
                if (o) return o[k];
            }, option[localStorage.getItem("language") || "zhCN"]);
        } 
    }
}

2. 创建语言模块json

<!-- assets/i18n/zh-CN.json -->
{
    "project": {
        "projectName": "项目名称"
    }
}
<!-- assets/i18n/en-US.json -->
{
    "project": {
        "projectName": "project name"
    }
}

3. 注册插件

import zhCN from "./assets/i18n/zh-CN.json";
import enUS from "./assets/i18n/en-US.json";
import { i18nPlugin } from "./plugins/i18n";

const app = createApp(App);
app.use(i18nPlugin, {
  zhCN,
  enUS,
});

4. 语言切换组件

<!-- components/ChangeLanguage.vue -->
<template>
  <a-select
    :value="language"
    @change="changeLanguage"
  >
    <a-select-option value="zhCN">中文</a-select-option>
    <a-select-option value="enUS">English</a-select-option>
  </a-select>
</template>

<script lang="ts"setup>
import {ref} from "vue";

// 将当前选择的语言存到localStorage中
const language = ref(localStorage.getItem("language") || "zhCN");
const changeLanguage = (value: string) => {
  language.value = value;
  localStorage.setItem("language", value);
  window.location.reload();
};
</script>

5. 使用插件(ts中使用全局需注意点)

<template>
	<ChangeLanguage />
</template>
<!-- component.vue -->
<script lang="ts" setup>
import { getCurrentInstance } from "vue";
import SelectLanguage from "@/components/SelectLanguage.vue";


// 通过getCurrentInstance()来获取当前组件实例
const instance = getCurrentInstance();
// 从当前组件实例中获取全局的 $t 函数
const $t = instance?.appContext.app.config.globalProperties.$t;

// 调用全局的 $t 函数进行文本翻译
const translatedText = $t('project.projectName');
console.log(translatedText);
</script>

网站公告

今日签到

点亮在社区的每一天
去签到