vue3 使用 vue-i18n 配置多语言环境

发布时间 2023-08-14 18:23:30作者: Li_pk

1. 插件地址:

Vue I18n官方文档
GitHub地址

2. 安装:

在 Vue 之后引入 vue-i18n,它会自动安装:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>

NPM:

npm install vue-i18n

Yarn:

yarn add vue-i18n

3. 使用:

① src 目录下新建 locales 文件夹存放相关文件

image

locales/index.js 中创建 i18n 实例,内容如下:

import { createI18n } from "vue-i18n";
import enUS from "./en-US/index";
import zhCN from "./zh-CN/index";
import zhHK from "./zh-HK/index";

const message = {
  enUS: {
    ...enUS,
  },
  zhCN: {
    ...zhCN,
  },
  zhHK: {
    ...zhHK,
  },
};

const i18n = createI18n({
  locale: "zhCN", // 设置语言类型
  legacy: false, // 如果要支持compositionAPI,此项必须设置为false;
  globalInjection: true, // 全局注册$t方法
  messages: message,
});

export default i18n;

en-US 等文件夹用于存放不同语言配置,例如:

// en-US/index.js
export default {
  message: {
    hello: 'hello world'
  }
};
// zh-CN/index.js
export default {
  message: {
    hello: '你好 世界'
  }
};
// ...

② main.js 中引入 i18n

import { createApp } from "vue";
import i18n from "./locales/index";

const app = createApp(App);
app.use(i18n);
app.mount("#app");

③ 页面中使用

<div id="app">
  <p>{{ $t("message.hello") }}</p>
</div>

④ script中使用

<script setup>
import { useI18n } from "vue-i18n";
import { computed } from "vue";

const { t, locale } = useI18n();

const changeLang = (lang) => {
  locale.value = lang;
  localStorage.setItem("LANG", lang);
};
const getCurrentLang = computed(() => {
  return locale.value;
});

console.log(getCurrentLang.value);
console.log(t("message.hello"));
</script>

4. 问题:

① 使用vite时控制台报错如下:

image
解决方法:vite中添加如下配置

resolve: {
  alias: [
    {
      find: "vue-i18n",
      replacement: "vue-i18n/dist/vue-i18n.cjs.js",
    },
  ],
},