Skip to content

Internationalization (i18n)

NovaStack supports multilingual functionality, allowing you to provide localized user experiences based on users' regions and preferences. This guide will walk you through how to implement and manage internationalization features in your project.

Configuring i18n

Installing Dependencies

Ensure that the necessary i18n dependency packages are installed. You can install them using the following command:

bash
npm install vue-i18n@9

Creating Language Files

Create different language JSON files in the locales directory. For example, en/common.json and zh/common.json represent English and Chinese language files respectively.

English Language File (locales/en/common.json)

json
{
  "welcome": "Welcome to NovaStack",
  "description": "A powerful framework for building applications."
}

Chinese Language File (locales/zh/common.json)

json
{
  "welcome": "欢迎使用 NovaStack",
  "description": "一个用于构建应用程序的强大框架。"
}

Configuring the i18n Module

Configure the i18n module in the i18n.config.ts file, loading language files and setting the default language.

typescript
import {createI18n} from "vue-i18n"
import en from "../locales/en/common.json"
import zh from "../locales/zh/common.json"

export default createI18n({
  legacy: false,
  locale: "en", // Default language
  fallbackLocale: "en", // Fallback language
  messages: {
    en,
    zh,
  },
})

Using Translations

In Vue components, you can use the $t method to access translation content.

Example Component

vue
<template>
  <div>
    <h1>{{ $t("welcome") }}</h1>
    <p>{{ $t("description") }}</p>
  </div>
</template>

<script setup lang="ts">
import {useI18n} from "vue-i18n"

const {t} = useI18n()
</script>

Switching Languages

You can dynamically switch the application's language by modifying the i18n's locale property.

Example Code

vue
<template>
  <div>
    <button @click="setLocale('en')">English</button>
    <button @click="setLocale('zh')">中文</button>
  </div>
</template>

<script setup lang="ts">
import {useI18n} from "vue-i18n"

const {locale} = useI18n()

const setLocale = (lang: string) => {
  locale.value = lang
}
</script>

By following these steps, you can implement and manage internationalization features in your NovaStack project, providing localized experiences for your users. If you have any questions or need further assistance, please feel free to contact our support team.