vue-i18n 的基本使用

官方文档

安装

npm
yarn
pnpm
bun
npm install vue-i18n@10

基本使用

在 locales 下创建index.js,负责导出国际化配置

/locales/index.js
import { createI18n } from "vue-i18n";
// 语言配置文件
import en from "./en.json";
import zh from "./zh-Cn.json";

const messages = {
  en,
  "zh-CN": zh,
};

const i18n = createI18n({
  legacy: false, // 设置为 false,启用 composition API 模式
  messages,
  locale: localStorage.getItem("lang") || "en", // 设置默认语言
  silentTranslationWarn: true,
  globalInjection: true, // 全局注入
});

export { i18n };

在 main.js 中引入

main.js
// ...
import { i18n } from "./locales";

// app 为Vue实例
app.use(i18n);

在 vue 中使用

<template>
  <div>
    <h1>{{ $t("hello") }}</h1>
  </div>
</template>

<script setup>
  // 只能在setup中这么写
  import { useI18n } from "vue-i18n";
  const { t } = useI18n();

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

在 js 文件中使用

// 引入
import { i18n } from "../locales";

// 调用
console.log(i18n.global.t("hello"));

使用变量,有对象和数组两种方式,这里只记录对象的使用方式

// 定义
const messages = {
  en: {
    hello: "hello {name}",
  },
  "zh-CN": {
    hello: "你好 {name}",
  },
};

// 使用
<div>{{ t('hello',{name:'张三'})}}</div>

console.log(i18n.global.t("hello", { name: "张三" }));
ON THIS PAGE