# i18n构建全局语言切换组件

# 1.store定义一个language变量

可以使用vuex 或者 pinia

示例使用pinia

export const GlobalStore = defineStore({
	// id: 必须的,在所有 Store 中唯一
	id: "GlobalState",
	// state: 返回对象的函数
	state: (): GlobalState => ({
		// token
		token: "",
		// language
		language: ""
	}),
	getters: {},
	actions: {
		// updateLanguage
		updateLanguage(language: string) {
			this.language = language;
		}
	},
	persist: piniaPersistConfig("GlobalState")
});

# 2、构建组件

<template>
	<el-dropdown trigger="click" @command="handleSetLanguage">
		<el-tooltip effect="dark" content="语言切换" placement="top">
			<i :class="'iconfont icon-zhongyingwen'" class="toolBar-icon"></i>
		</el-tooltip>
		<template #dropdown>
			<el-dropdown-menu>
				<el-dropdown-item :disabled="language && language === 'zh'" command="zh">简体中文</el-dropdown-item>
				<el-dropdown-item :disabled="language === 'en'" command="en">English</el-dropdown-item>
			</el-dropdown-menu>
		</template>
	</el-dropdown>
</template>

<script setup lang="ts">
import { computed, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { GlobalStore } from "@/stores";
import { getBrowserLang } from "@/utils/util";

const i18n = useI18n();
const globalStore = GlobalStore();
const language = computed((): string => globalStore.language);

// 切换语言
const handleSetLanguage = (lang: string) => {
	i18n.locale.value = lang;
	globalStore.setLanguage(lang);
};

onMounted(() => {
	handleSetLanguage(language.value || getBrowserLang());
});
</script>

# 使用组件

<Language id="Language" class="toobar-icon" />

import Language from "./components/Language.vue";

# 其他扩展

  • 1、获取浏览器默认语言
/**
 * @description 获取浏览器默认语言
 * @return string
 */
export function getBrowserLang() {
	let browserLang = navigator.language ? navigator.language : navigator.browserLanguage;
	let defaultBrowserLang = "";
	if (browserLang.toLowerCase() === "cn" || browserLang.toLowerCase() === "zh" || browserLang.toLowerCase() === "zh-cn") {
		defaultBrowserLang = "zh";
	} else {
		defaultBrowserLang = "en";
	}
	return defaultBrowserLang;
}

  • 2.创建一个window.d.ts
// * global
declare global {
	interface Navigator {
		msSaveOrOpenBlob: (blob: Blob, fileName: string) => void;
		browserLanguage: string;
	}
}

export { };

  • 3.effect可以通过props传递
Last Updated: 3/27/2023, 11:02:53 PM