SoFunction
Updated on 2025-04-12

How to switch Chinese and English display with Vue3 for example

Switching the display language in Vue 3 usually involves using the internationalized (i18n) library, such asvue-i18n. Here is a basic example showing how to set and switch the display language.

1. Install vue-i18n

First, make sure that your project hasvue-i18n. You can install it using the following command:

npm install vue-i18n

2. Set vue-i18n

Configure in your Vue 3 appvue-i18n. In the main file (e.g.) configure it:

import { createApp } from 'vue';
import App from './';
import { createI18n } from 'vue-i18n';

// Define translation informationconst messages = {
  en: {
    welcome: 'Welcome',
    language: 'Language'
  },
  zh: {
    welcome: 'welcome',
    language: 'language'
  }
};

// Create an i18n instanceconst i18n = createI18n({
  locale: 'en', // Default language  fallbackLocale: 'en',
  messages,
});

const app = createApp(App);

// Use i18n(i18n);
('#app');

3. Use internationalization in components

In the component you can use$tMethod to get the translation string. For example:

<template>
  <div>
    <p>{{ $t('welcome') }}</p>
    <select v-model="currentLanguage" @change="changeLanguage">
      <option value="en">English</option>
      <option value="zh">Chinese</option>
    </select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentLanguage: 'en'
    };
  },
  methods: {
    changeLanguage() {
      this.$ = ;
    }
  }
};
</script>

In this example, when the user selects a different language, it is calledchangeLanguageMethod, this method will changei18nExamplelocale, thereby switching the language display of the application.

4. Dynamic loading of language packs (optional)

If your application supports many languages, you may need to load the language pack on demand. You canchangeLanguageDynamically import language packages in the method:

methods: {
  async changeLanguage() {
    const messages = await import(`./locales/${}.json`);
    this.$(, );
    this.$ = ;
  }
}

This can avoid loading all language packs at once and improve the performance of the application.

Summarize

This is the end of this article about how to switch Chinese and English displays with Vue3. For more related content on switching Chinese and English displays with Vue3, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!