Vue3实现国际化多语言切换

一、安装包vue-i18n

npm i vue-i18n --save

二、创建操作Cookie工具

把用户选择的语言存在Cookie中

npm install --save js-cookie

在util目录下创建cookies.ts文件

import Keys from "@/constant/key";
import Cookies from "js-cookie";
export const getLanguage = () => Cookies.get(Keys.languageKey);
export const setLanguage = (language: string) =>
  Cookies.set(Keys.languageKey, language);

三、创建好语言包messages,包含自己建的en.ts,zh-cn.ts 和 element-plus语言包

在src目录下创建locales文件夹,文件夹下创建en.ts,zh-ch.ts文件;

en.ts

export default {
  login: {
    title: "Login Form",
    logIn: "Login",
    username: "Username",
    password: "Password",
    any: "any",
    thirdparty: "Or connect with",
  },
};

zh-ch.ts

export default {
  login: {
    title: "系统登录",
    logIn: "登录",
    username: "账号",
    password: "密码",
    any: "随便填",
    thirdparty: "第三方登录",
  },
};

四、创建i18n

在locales文件夹下 创建index.ts文件

import { createI18n } from "vue-i18n"; // import from runtime only
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { getLanguage } from "@/utils/cookies";

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import elementEnLocale from "element-plus/lib/locale/lang/en";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import elementZhLocale from "element-plus/lib/locale/lang/zh-cn";
// User defined lang
import enLocale from "./en";
import zhLocale from "./zh-cn";
const messages = {
  en: {
    ...enLocale,
    ...elementEnLocale,
  },
  "zh-cn": {
    ...zhLocale,
    ...elementZhLocale,
  },
};

export const getLocale = () => {
   //读取cookie存入的当前语言
  const cookieLanguage = getLanguage();
  //如果有返回当前语言
  if (cookieLanguage) {
    return cookieLanguage;
  }
  //如果没有,获取系统语言
  const language = navigator.language.toLowerCase();
  //获取messages 语言 遍历
  const locales = Object.keys(messages);
  for (const locale of locales) {
  //如果messsage 包里面有系统语言返回
    if (language.indexOf(locale) > -1) {
      return locale;
    }
  }
  // 默认语言 简体中文
  return "zh";
};
const i18n = createI18n({
  globalInjection: true,
  legacy: false,
  locale: getLocale(),
  messages: messages,
});
export default i18n;

五、在main.ts中注册

import { createApp } from "vue";
import App from "./App.vue";
import i18n from "@/locales/index";
createApp(App).use(store).use(router).use(i18n).use(ElementPlus).mount("#app");

六、页面使用

<script lang="ts" setup>
import LangSelect from "@/components/lang_select/langSelect.vue";
import { reactive } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
// do not use same name with ref
const form = reactive({
  name: "",
});
</script>
<template>
  <div>
    <div style="margin: 50px">
      {{ $t("login.title") }}
    </div>
    <el-form :model="form" label-width="120px">
      <el-form-item :label="$t('login.username')">
        <el-input v-model="form.name" :placeholder="t('login.username')" />
      </el-form-item>
    </el-form>
  </div>
</template>

七、语言切换

这里就是切换后存到cookies中,写法有千万…

<script setup lang="ts">
import {} from "vue";
import { useI18n } from "vue-i18n";
import { setLanguage } from "@/util/cookies";
const { locale } = useI18n();
const languages = [
  { name: "en", value: "en" },
  { name: "中文", value: "zh-cn" },
];
const handleSetLanguage = (lang: string) => {
  locale.value = lang;
  setLanguage(lang);
};
</script>
<template>
  <el-dropdown style="margin-top: 15px">
    <span class="el-dropdown-link">
      <el-button type="text">
        <i class="iconfont icon-duoyuyan menuImgColor"></i>
      </el-button>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          v-for="item in languages"
          :key="item.value"
          @click="handleSetLanguage(item.value)"
        >
          <span>{{ item.name }}</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<style scoped lang="scss">
.menuImgColor {
  color: white;
  font-size: 20px;
  line-height: 50px;
  width: 50px;
}

.menuImgColor:hover {
  background-color: #c9c9c9;
}
</style>

八、Element UI Plus 语言适配

采用全局配置组件 el-config-provider 进行语言适配

<script lang="ts" setup>
import { useI18n } from "vue-i18n";
const { locale, messages } = useI18n();
</script>
<template>
  <div class="page">
    <el-config-provider :locale="messages[locale]">
      <div style="padding: 20px">
        <router-view v-slot="{ Component }">
          <transition>
            <div>
              <keep-alive>
                <component :is="Component" v-if="route.meta.keepAlive" />
              </keep-alive>
              <component :is="Component" v-if="!route.meta.keepAlive" />
            </div>
          </transition>
        </router-view>
      </div>
    </el-config-provider>
  </div>
</template>

<style scoped>
.page {
  width: 100%;
  height: 100%;
  background: #fff;
  overflow-y: auto;
}
</style>

你可能感兴趣的:(前端,elementui,vue.js)