Cookie Consent by Free Privacy Policy Generator 📌 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 🌐


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

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!"
}

ja.json

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

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

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');

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;

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>

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>

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,
    }),
  ],
});

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! 🚀👩‍💻👨‍💻

...

✅ Moving From Vue 1 To Vue 2 To Vue 3: A Case Study Of Migrating A Headless CMS System


📈 38.46 Punkte

✅ Building a multi-language app with Vue JS. 🌐


📈 27.64 Punkte

✅ Building a Simple Electron Application with Vue.js 🚀🔧


📈 27.32 Punkte

✅ Building Simple CRM with Vue: Document CRUD Operations


📈 27.32 Punkte

✅ How To Use META AI (Complete Tutorial) Beginner Tutorial (LLAMA 3 Tutorial)


📈 26.91 Punkte

✅ [20120902] - XSS vulnerability in language switcher module


📈 26.33 Punkte

✅ [20180602] - XSS vulnerability in language switcher module


📈 26.33 Punkte

✅ Language Switcher Module on Joomla Reflected cross site scripting


📈 26.33 Punkte

✅ Language Switcher Module auf Joomla! Reflected Cross Site Scripting


📈 26.33 Punkte

✅ Creating a Simple Proxy Switcher in Node.js


📈 26.01 Punkte

✅ Tuned Switcher 0.4.0 - simple utility for managing performance profiles


📈 26.01 Punkte

✅ Figma to Vue: Convert Designs to Clean Vue Code in a Click


📈 25.64 Punkte

✅ Efficiently Managing Remote Data in Vue with Vue Query


📈 25.64 Punkte

✅ Enhance the drag and drop of your Vue 3 application with Vue Fluid DnD


📈 25.64 Punkte

✅ HTML & Vue.js, a secrete you may not know about Vue


📈 25.64 Punkte

✅ Vue Designer 1.4 - Desktop editor to visually design Vue applications.


📈 25.64 Punkte

✅ 500+ Vue.js Tailwind CSS UI Components - TailGrids Vue


📈 25.64 Punkte

✅ Easy Vue internationalization - guide to the Vue I18n plugin


📈 25.64 Punkte

✅ Vue i18n – So erstellst Du mehrsprachige Vue.js Anwendungen!


📈 25.64 Punkte

✅ NativeScript-Vue 2.0 erschienen: Native Mobile-Apps mit Vue


📈 25.64 Punkte

✅ Tutorial: Creación de un Proyecto Vue desde Cero e Integración con Bootstrap


📈 21.79 Punkte

✅ Bangla Tutorial: Design Responsive Headers Using Vuetify 3 & Vue.js 3 | Navigation Drawers Vuetify


📈 21.79 Punkte

✅ Tutorial: How to Implement Passkeys in Vue.js Apps


📈 21.79 Punkte

✅ Vue.js Tutorial: Getting Started & 10 Best Practices


📈 21.79 Punkte

✅ heise+ | Vue.js-Tutorial, Teil 3: Externe Ressourcen und TypeScript


📈 21.79 Punkte

✅ A simple explanation of Adapter Pattern with Vue.js


📈 20.23 Punkte

✅ Creating a Simple CRUD Application with Vue.js


📈 20.23 Punkte

✅ How To Create A Simple Dynamic Pagination From Scratch In Vue


📈 20.23 Punkte

✅ Build a Simple CRUD App with Spring Boot and Vue.js


📈 20.23 Punkte

✅ Building a Vue 3 Component Library from Scratch (Part 3): Environment Configuration


📈 19.91 Punkte

✅ Building a Vue 3 Component Library from Scratch (Part 2): Monorepo


📈 19.91 Punkte

✅ Building a Vue 3 Component Library from Scratch (Part 1): Introduction


📈 19.91 Punkte











matomo

Datei nicht gefunden!