DEV Community

Cover image for Building a simple language switcher in a vue.js: Step-by-step tutorial 🌐

Building a simple language switcher in a vue.js: Step-by-step tutorial 🌐

Creating a multilingual application can dramatically increase its accessibility and reach. This blog post guides you through creating a language switcher component in a Vue.js application using the vue-i18n plugin. This functionality allows users to switch between different languages, enhancing accessibility and reaching a broader audience.

Language switcher

Step 1: Setting up Your Project Structure 📁

Before diving into the code, let's ensure our project is properly structured. A dedicated lang folder is created within the src directory to store language files (e.g., en.json, ja.json) for better organization. This is where we'll hold our language files, as shown in the screenshot below:

Src folder

Having a separate folder for each language keeps things organized, enabling easier management of translations.

Also, here is the sample json file of en and ja

en.json



{
  "welcome": "Welcome!"
}


Enter fullscreen mode Exit fullscreen mode

ja.json



{
  "welcome": "ようこそ!"
}


Enter fullscreen mode Exit fullscreen mode

Step 2: Configuring vue-i18n 🛠️

First, let's install the vue-i18n package by running the following command in your project:



npm install vue-i18n


Enter fullscreen mode Exit fullscreen mode

Next, we need to configure the vue-i18n plugin. The main.js file is updated to import and use the i18n instance, making localization features accessible throughout the app.



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

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


Enter fullscreen mode Exit fullscreen mode

Step 3: Creating the i18n.js File 📝

This file serves as the core for handling translations. It uses the createI18n function to initialize vue-i18n.
Language files (en.json and ja.json) are imported and assigned to the messages option.

A fallback mechanism is set using fallbackLocale to ensure a default language displays if the chosen language isn't available.
legacy is set to false for improved compatibility.



import { createI18n } from 'vue-i18n';
import en from './lang/en/en.json';
import ja from './lang/ja/ja.json';

const i18n = createI18n({
  legacy: false,
  locale: localStorage.getItem('lang') || 'en',
  fallbackLocale: 'en',
  messages: {
    en,
    ja,
  },
});

export default i18n;


Enter fullscreen mode Exit fullscreen mode

Step 4: Crafting a LanguageSwitcher Component 🔄

A new Vue component named LanguageSwitcher.vue is created.



<template>
  <div>
    <button @click="setLanguage('en')" style="margin-right: 8px">English</button>
    <button @click="setLanguage('ja')">Japanese</button>
  </div>
</template>

<script setup>
import { useI18n } from 'vue-i18n';
import { watchEffect } from 'vue';

const { locale } = useI18n();

const setLanguage = (newLang) => {
  locale.value = newLang;
  localStorage.setItem('lang', newLang);
};

watchEffect(() => {
  const storedLang = localStorage.getItem('lang');
  if (storedLang) {
    locale.value = storedLang;
  }
});
</script>


Enter fullscreen mode Exit fullscreen mode

Key Functionalities:

setLanguage Function:

  • This function takes a new language code (newLang) as input.
  • It updates the locale.value of the i18n instance with the new language.
  • The user's preference is saved to localStorage using localStorage.setItem('lang', newLang).

watchEffect:

  • This monitors changes in localStorage.
  • If a stored language preference (lang) exists in localStorage, it retrieves the value and updates the locale.value of the i18n instance accordingly. This ensures the app reflects the user's saved language preference upon loading.

In essence, this component provides a user interface to switch languages and persists the user's choice in localStorage.

Step 5: Updating the App.vue File 🌟

Now, let's use our LanguageSwitcher in the main App.vue:



<template>
  <div>
    <LanguageSwitcher />
    <p>{{ t('welcome') }}</p>
  </div>
</template>

<script setup>
import { useI18n } from 'vue-i18n';
import LanguageSwitcher from './components/LanguageSwitcher.vue';

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


Enter fullscreen mode Exit fullscreen mode

Here, the t function from useI18n is used to display the translated "welcome" message based on the current locale.

Step 6: Handling vue-i18n Legacy Console Error 🚫

If you encounter a legacy mode error related to vue-i18n, update your vite.config.js file as instructed.



import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [
    vue({
      reactivityTransform: true,
    }),
  ],
});


Enter fullscreen mode Exit fullscreen mode

And remember to set the legacy: false option in the i18n.js file, as shown in Step 3.

Live Demo 🎮

To see this language switcher in action, visit the live demo

https://stackblitz.com/edit/vuejs-language-switcher-i18n?file=README.md


Conclusion 🎉

By following these steps, you can create a functional language switcher in your Vue.js application using vue-i18n. This enhances user experience by catering to a wider audience and providing language options. Remember to thoroughly test the switcher and translations for a seamless multilingual experience.

Feel free to share your thoughts and opinions and leave me a comment if you have any problems or questions. 😎😎

Till then, Keep on Hacking, Cheers

Happy coding! 🚀👩‍💻👨‍💻

Top comments (0)