Vue3 + element-plus 国际化

前言

本案适用于 Vue3+ element-plus 项目国际化的实现,支持多种语言,其中包括了常规内容的国际化和 element-plus 的国际化

插件:i18n 、vue-i18n

官方案例:https://element-plus.gitee.io/zh-CN/guide/i18n.html

1.安装插件

安装 i18n

npm install i18n

安装 vue-i18n

npm install vue-i18n

2.文件配置

当前案例实现的是中文和英文两种语言的切换,以下文件只配置两种语言,你可以根据自己实际情况配置更多语种

2.1 新建 lang 文件夹 和 watch-local-storage.js 语言持久化函数工具文件

在 src 文件夹在新建  lang 文件夹,文件夹内分别新建 i18n.js 、 index.js、 en.js、 zh-cn.js 四个 js 文件,如下

├── src                                   
│   │── lang  [国际化文件夹]                          
│   │   │── index.js  [输出文件]               
│   │   │── i18n.js   [国际化配置]                                
│   │   │── zh-cn.js  [中文]                                          
│   │   │── en.js     [英文]
|   |——util [工具库文件]
|   |   |——watch-local-storage.js      

2.2 文件夹配置

在 zh-cn.js  文件中写入

const zhCN = {
  message: {
    Hello: "您好",
    WelcomeToSiipAdmin: "欢迎来到钢构管家运营大厅",
  },
};
export default zhCN;

 在 en.js 文件中写入

const en = {
  message: {
    Hello: "Hello",
    WelcomeToSiipAdmin: "Welcome to the steel structure butler operation hall",
  },
};
export default en;

 在 index.js 文件中写入

import en from "./en";
import zhCN from "./zh-cn";
export default {
  en,
  zhCN,
};

 在 i18n.js 文件中写入

import { createApp } from "vue";
import App from "../App.vue";
import { createI18n } from "vue-i18n";
import messages from "./index";
const app = createApp(App);
/**
 * locale  持久化配置
 */
const locale = localStorage.getItem("locale")
  ? localStorage.getItem("locale") === "zh-cn"
    ? "zhCN"
    : "en"
  : "zhCN";
const i18n = createI18n({
  legacy: false,
  locale,
  messages,
});
export default function (app) {
  app.use(i18n);
}

在 watch-local-storage.js 文件中写入

/* 监听localStorage 变化 */
export const dispatchEventStorage = () => {
  const signSetItem = localStorage.setItem;
  localStorage.setItem = function (key, val) {
    let setEvent = new Event("setItemEvent");
    setEvent.key = key;
    setEvent.newValue = val;
    window.dispatchEvent(setEvent);
    signSetItem.apply(this, arguments);
  };
};
/* 设置localStorage locale 语言版本  */
export const languageSet = () => {
  if (localStorage.getItem("locale")) {
    return localStorage.getItem("locale");
  }
  return localStorage.setItem("locale", "zhCN");
};

2.3 全局注册

在 main.ts  文件中

import App from "./App.vue";
import { createApp } from "vue";
import ElementPlus from "element-plus";
import locale from "element-plus/dist/locale/zh-cn.mjs";
import I18n from "@/lang/i18n.js"; // 引入
const app = createApp(App);
app.use(ElementPlus, {
  locale,
});
app.use(I18n); //挂载
app.mount("#app");

到这里,国际化 `i18n` 的基本配置已经完成了,但是这不包括 `element-plus` 的国际化,而 `element-plus` 的国际化是要引入对应语言包,然后修改 `locale` 的值即可,后面详细讲

3.使用方法

如以上的配置你准确无误的配置好了,那么你可以在你的 `vue` 文件的 `template` 标签中使用 `$t()` 了

<p>{{ $t('message.Hello') }},{{ $t('message.WelcomeToSiipAdmin') }}</p>

4.语言切换

语言切换包括两点:

一、我们自己配置的语言切换

二、element-plus 组件语言的切换

4.1 在切换语言的 vue 文件的 template 标签内

 此处可根据实际 ui 自定义你自己的标签

<el-dropdown @command="handleCommand">
  <span class="language">{{ locale === 'en' ? '英文' : '中文' }}</span>
  <template #dropdown>
    <el-dropdown-menu>
      <el-dropdown-item command="中文" @click="changeLang('zh-cn')">中文</el-dropdown-item>
      <el-dropdown-item command="英文" @click="changeLang('en')">英文</el-dropdown-item>
    </el-dropdown-menu>
  </template>
</el-dropdown>

4.2 在切换语言的 vue 文件的 script 标签内

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useI18n } from "vue-i18n";
import { languageSet } from '@/util/watch-local-storage.js';  //持久化处理函数
const language = ref(languageSet());
const { locale } = useI18n();
/* 语言切换方法 */
const changeLang = (val) => {
    locale.value = val === 'zh-cn' ? 'zhCN' : val;
    localStorage.setItem("locale", val);
};
</script>

5.持久化配置

以上步骤你会发现一些持久化配置代码已经有在写了,但是切换的时候好像 element-plus 组件的语言没有跟随切换,我们还缺少这一步

在 app.vue 文件中写入以下代码

<template>
  // element-plus 组件语言切换的关键标签 el-config-provider
  <el-config-provider :locale="locale">
    <div id="sub-page">
      <router-view />
    </div>
  </el-config-provider>
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import { ElConfigProvider } from "element-plus"; // 引入标签用作语言切换
import zhCn from "element-plus/dist/locale/zh-cn.mjs"; // 中文包
import en from "element-plus/dist/locale/en.mjs"; // 英文包
import { languageSet } from "@/util/watch-local-storage.js"; // 语言切换函数
const language = ref(languageSet());
const locale = computed(() => (language.value === "zh-cn" ? zhCn : en));
window.addEventListener("setItemEvent", function (e: any) {
  // 监听localStorage  locale 值的变化
  if (e.key === "locale") {
    language.value = e.newValue;
  }
});
</script>

结语

前端国际化已经是很常见的开发需求了,所以也是作为一个前端开发工程师应有的必备技能。而项目完整的国际化是涉及常规内容的国际化和组件的国际化的,并且有持久化的应用场景需求的。

如果你能跟着步骤实现项目的持久化功能,请为我点赞

欢迎大家的及时指正,共同进步

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Vue 3.0+Element-Plus开发后台管理系统的步骤: 1.首先,确保你已经安装了Node.js和npm包管理器。 2.使用以下命令安装Vue CLI 4: ```shell npm install -g @vue/cli ``` 3.使用Vue CLI创建一个新项目: ```shell vue create my-project ``` 4.在创建项目时,选择使用Vue 3.0版本,并启用class-style component语法: ```shell ? Please pick a preset: Manually select features ? Check the features needed for your project: Choose Vue version, Babel, Router, Vuex, CSS Pre-processors, Linter, Unit ? Choose a version of Vue.js that you want to start the project with 3.x (Preview) ? Use class-style component syntax? Yes ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? No ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass) ? Pick a linter / formatter config: ESLint with error prevention only ? Pick additional lint features: Lint on save ? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files ``` 5.安装Element-Plus和Echarts 5.0: ```shell npm install element-plus [email protected] ``` 6.在main.js中引入Element-Plus和Echarts: ```javascript import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' import echarts from 'echarts' const app = createApp(App) app.use(store) app.use(router) app.use(ElementPlus) app.config.globalProperties.$echarts = echarts app.mount('#app') ``` 7.现在你可以开始使用Element-Plus和Echarts来开发你的后台管理系统了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值