Skip to content
On this page

i18n 文本多语言解决方案

javascript
import { createI18n } from 'vue-i18n'; // 引入第三方最新的i18n注意版本

/**
 * @description: 加载当前配置的语言配置目录,随意添加
 */
export function loadLang() {
  const modules: Record<string, any> = import.meta.glob('./lang/*.ts', { eager: true });
  const langs: Record<string, any> = {};

  for (const path in modules) {
    const name = path.replace(/(\.\/lang\/|\.ts)/g, '');
    langs[name] = modules[path].lang;
  }
  return langs;
}

export const i18n = createI18n({
  // globalInjection: true,
  // legacy: false,
  locale: 'zh-cn', // 默认语言,当前这里的数据要跟配置的lang目录下面的文件名字前缀一致
  fallbackLocale: 'zh-cn',
  messages: loadLang(), // 记载当前引入的语言目录的处理过后的数据
});

/**
 * @description: 切换当前多语言
 */
export function setLang(locale?: string) {
  if (locale) {
    localStorage.setItem('lang', locale);
  }
  i18n.global.locale = locale || localStorage.getItem('lang') || '';
}

css图片解决方案

目前在业务开发中,css的样式多语言也会经常用到,可能一些图片的字体比较复杂,代码很难实现。或者我们为了减少多语言的配置,加快开发效率也会使用多语言的配置,目前这里提供scss的图片多语言的方案

css
@mixin main-lang-bg($width, $height, $preUrl, $posUrl) {
  width: $width;
  height: $height;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  @include loop-lang-bg($preUrl, $posUrl);
}
// 背景图多语言
@mixin loop-lang-bg($preUrl, $posUrl) {
  $list: zh-cn, en-us; // 配置需要的多语言,根据项目来
  @each $i in $list {
    &.#{$i} {
      background-image: url('#{$preUrl}/#{$i}/#{$posUrl}');
    }
  }
}

定义图片的目录格式

bash
├── button
   ├── en-us
      └── confirm.png
   ├── zh-cn
      └── confirm.png

HTML的使用方式

html
<template>
 <div :class="['btn-confirm', i18n.global.locale]"></div>
</template>
<script lang="ts" setup name="HomePage">
    import { i18n } from '/@/i18n';
</script>
<style lang="scss" scoped>
    .btn-confirm {
        @include main-lang-bg(302px, 82px, '/@/assets/button', 'confirm.png');
    }
</style>

Released under the MIT License.