Copied!
Vue
Mastering Vue 3 Localization: A Comprehensive Tutorial
vue 3 localization.jpg
Shahroz Javed
Feb 24, 2024 . 78 views

Table Of Contents

 
 

Introduction:

Welcome to our Vue 3 localization tutorial! Today, we'll show you how to make your Vue.js app speak different languages easily. In the ever-changing world of web development, keeping up with the latest tools is important. Vue 3 is a cool JavaScript framework, and adding localization will make your app user-friendly for people around the world. Let's get started and make your Vue 3 app more versatile!

 

install vue-i18n:

npm i vue-i18n
          
 

Create vue-i18n instance:

Inside data.js we will have locales supported by our app. so we can access it anywhere in our app as needed.

export const locales = ["en", "ur"];

In our config/i18n.js

import { createI18n } from "vue-i18n";
import ur from "../lang/ur.json";
import en from "../lang/en.json";
import { locales } from "../data";

// 2. Create i18n instance with options
const supportedLocales = locales;
const userLocale = localStorage.getItem("locale");
const locale = supportedLocales.includes(userLocale) ? userLocale : "en";
const i18n = createI18n({
    locale: locale, // set locale
    fallbackLocale: "en", // set fallback locale
    messages: {
        en: en,
        ur: ur,
    },
});

export default i18n;            
          

In main.js import 1i8n.js

import i18n from './config/i18n.js'

app.use(i18n)
          
 

App Language Switcher:

<select v-model="currentLocale" @change="setLocale" class="form-select">
  <option v-for="locale in locales" :key="locale">{{ locale }}</option>
</select>

<script>
import { locales } from '../../data';
export default {
  name: 'NavbarComponent',
  data() {
    return {
      locales: locales,
      currentLocale: localStorage.getItem('locale') || 'en'
    }
  },
  methods: {
    setLocale() {

      localStorage.setItem('locale', this.currentLocale)
      this.$i18n.locale = this.currentLocale;
    }
  }
}
</script>
          
 

Conclusion:

That's it! You have successfully implemented localization for your vue 3 app.

13 Shares