<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Mehrzi</title>
    <description>The latest articles on DEV Community by Mehrzi (@chaimamehrzi).</description>
    <link>https://dev.to/chaimamehrzi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1259447%2Fd7a98fc4-196c-4a3b-b3ec-9484c29f5ee0.png</url>
      <title>DEV Community: Mehrzi</title>
      <link>https://dev.to/chaimamehrzi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/chaimamehrzi"/>
    <language>en</language>
    <item>
      <title>From Basics to Advanced: Vue.js Internationalization Explained</title>
      <dc:creator>Mehrzi</dc:creator>
      <pubDate>Mon, 29 Jan 2024 12:34:39 +0000</pubDate>
      <link>https://dev.to/chaimamehrzi/from-basics-to-advanced-vuejs-internationalization-explained-1758</link>
      <guid>https://dev.to/chaimamehrzi/from-basics-to-advanced-vuejs-internationalization-explained-1758</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
In today's globalized world, it's crucial for web developers to create applications that can be easily localized for users from different regions and cultures. As we know, people around the world speak many languages. &lt;/p&gt;

&lt;p&gt;So, if we want our application to be accessible to everyone, it is necessary to create it in their native language and that's where internationalization is one of the best ways to make your web application accessible to all the people around the world providing them with a better user experience. If we look at it from a business perspective, internationalization and translation aid in strengthening global presence, consequently generating more revenue.&lt;/p&gt;

&lt;p&gt;Join me as we unravel the tapestry of internationalization with the Vue internationalization example, weaving together the threads of culture, language, and seamless user experiences.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tutorial Goal: Vue Internationalization Tutorial with Vue l18n&lt;/strong&gt;&lt;br&gt;
In this tutorial, you will learn about the Vue I18n plugin and explore how to implement internationalization and translation in our VueJS web application. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Vue I18n ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You must be wondering what is Vue I18n and its specific role in the journey toward internationalizing our web applications. Vue I18n is a localization library for Vue.js that helps developers easily handle application translations. It provides a simple and flexible API to integrate translations into Vue components, which makes creating multi-language apps almost effortless. With Vue I18n, you can define translation messages in different languages and easily switch between them based on the user's locale. It also supports multiple advanced features like dynamic translations or pluralization which makes it a truly comprehensive solution for Vue internationalization&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Project Set-Up&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, let's create a new Vue.js project using the Vue CLI. If you don't have the Vue CLI installed, you can just follow this command to install it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g @vue/cli
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, create a new project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;vue create vue-i18n-tutorial

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and don't forget to change the project directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd vue-i18n-tutorial
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Installing and configuring Vue I18n&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As you know we need Vue I18n to implement internationalization. Install it using the following command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;vue add i18n

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will see now how the Vue CLI is going to do all the required setup for you by creating a locale folder and an en.json file as our default language file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating translation files&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create translation files for each language you want to support. For example, create a fr.json for French translations :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "greeting": "Bonjour!"
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and a de.json for German translations :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "greeting": "Hallo!"
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;App.vue&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now we need to edit App.vue as follows and rename the generated HelloWorld.vue to HelloI18n.vue&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;template&amp;gt;
  &amp;lt;div id="app" class="container"&amp;gt;
    &amp;lt;div class="jumbotron"&amp;gt;
      &amp;lt;h1 class="display-4"&amp;gt;Vue Internationalization App&amp;lt;/h1&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;HelloI18n /&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/template&amp;gt;

&amp;lt;script&amp;gt;
import HelloI18n from "./components/HelloI18n.vue";

export default {
  name: "App",

  components: {
    HelloI18n,
  },
};
&amp;lt;/script&amp;gt;

&amp;lt;style&amp;gt;
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
&amp;lt;/style&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Add Vue18In in our template&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the HelloI18n.vue file remove everything and add the below one as an example :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;template&amp;gt;
  &amp;lt;div&amp;gt;
    &amp;lt;h1&amp;gt;
      {{ $t('language_select_info') }}
    &amp;lt;/h1&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;select v-model="$i18n.locale"&amp;gt;
        &amp;lt;option
          v-for="(langnguage, i) in languages"
          :key="langnguage"
          :value="langnguage"&amp;gt;
          {{ langnguage }}
        &amp;lt;/option&amp;gt;
      &amp;lt;/select&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/template&amp;gt;
&amp;lt;script&amp;gt;
export default {
    data(){
    return {
      languages: ['en', 'de', 'fr']
    }
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, as you can see, we have used language_select_info inside our template. Edit all the JSON files with this key and its translated value respective to the language as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//en.json
"language_select_info": "Select the language you want to use"

//de.json
"language_select_info": "Wählen Sie die Sprache aus, die Sie verwenden möchten"

//fr.json
"language_select_info": "Sélectionnez la langue que vous souhaitez utiliser"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For a better structure of our code, Create a plugins directory and move the previous i18n.js file from the root folder to the plugins folder. &lt;/p&gt;

&lt;p&gt;Now let's try to run our web app for the first time don't forget to use this command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run serve 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will look like this : &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6n78dc5d5i5h0fcz4x3x.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6n78dc5d5i5h0fcz4x3x.PNG" alt="Image description" width="800" height="135"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Using Browser's default language&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The application will use the default language set by the browser, which is English, as we haven't selected a default language for it. Let's say that even though the browser's default language is not English, your application still uses English. In that scenario, you will need to use the Select option to manually change the language.&lt;/p&gt;

&lt;p&gt;Modify the file i18n.js. Assign the browser's default language detection API, navigator.language, to the locale exported variable. The default language, such as en-GB or en-IN, is typically prefixed with the language of the browser. Since we only require the first section for our application, navigator.language.split('-')[0] has been used:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// plugins/i18n.js
export default new VueI18n({
  locale:
    navigator.language.split('-')[0] || process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages()
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s assume that we have region-specific languages in our app. We normally follow the naming convention in which we suffix the region’s short name after languages like en-GB.json and en-IN.json. To fetch the right language for the user’s region, we need to add the following code to our application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function checkDefaultLanguage() {
  let matched = null
  const languages = Object.getOwnPropertyNames(loadLocaleMessages())
  languages.forEach(language =&amp;gt; {
    if (language === navigator.language) {
      matched = language
    }
  })
  if (!matched) {
    languages.forEach(language =&amp;gt; {
      if (language === navigator.language.split('-')[0]) {
        matched = language
      }
    })
  }
  if (!matched) {
    languages.forEach(language =&amp;gt; {
      if (language.split('-')[0] === navigator.language.split('-')[0]) {
        matched = language
      }
    })
  }
  return matched
}


export const selectedLocale =
  checkDefaultLanguage() || process.env.VUE_APP_I18N_LOCALE || 'en'
export const languages = Object.getOwnPropertyNames(loadLocaleMessages())
export default new VueI18n({
  locale: selectedLocale,
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages()
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, I separated the browser default language and our JSON filenames and then matched en-GB with en-IN, which is a better choice than presenting Dutch. As you can see, I've exported a couple more constants from the file to utilize later in our project.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Persisting Language Preferences&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s change the language to German using our created language list. You can see our texts get translated into German but if you refresh the web page, You can see the translated Hindi message is reset to English again!&lt;/p&gt;

&lt;p&gt;This does not make sense. We can enhance it. We need to save the user's preference and apply it in our application every time the user visits or reloads the sites. We can use the browser's localStorage to save and get from it every time, or we can use one plugin - vuex-persistedstate - that accomplishes the same thing for us automatically.&lt;/p&gt;

&lt;p&gt;First, we need to install the plugin:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save vuex-persistedstate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and then we need to change some files : &lt;/p&gt;

&lt;p&gt;//store/index.js :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Vuex from 'vuex'
import Vue from 'vue'
import i18n, { selectedLocale } from '@/plugins/i18n'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    locale: i18n.locale
  },
  mutations: {
    updateLocale(state, newLocale) {
      state.locale = newLocale
    }
  },
  actions: {
    changeLocale({ commit }, newValue) {
      // update it in i18n plugin
      i18n.locale = newValue
      commit('updateLocale', newValue)
    }
  },
  plugins: [createPersistedState()]
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;//main.js :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Vue from "vue";
import App from "./App.vue";
import i18n from "./plugins/i18n";
import store from "./store";

Vue.config.productionTip = false;

new Vue({
  i18n,
  store,
  render: (h) =&amp;gt; h(App),
}).$mount("#app");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of using the component's local variable, let's utilize vuex-persistedstate to save and update changes in the user-selected language. Our plugin will save the user-selected language in localStorage. When the user reloads or reopens the page, our plugin retrieves the language from localStorage, uses it in the app, and displays its value in the language option dropdown.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;template&amp;gt;
  &amp;lt;div class="lang-dropdown"&amp;gt;
    &amp;lt;select v-model="lang"&amp;gt;
      &amp;lt;option
        v-for="(language, i) in languages"
        :key="language"
        :value="language"&amp;gt;
        {{ language }}
      &amp;lt;/option&amp;gt;
    &amp;lt;/select&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/template&amp;gt;
&amp;lt;script&amp;gt;
import { languages } from '@/plugins/i18n'
export default {
  computed: {
    lang: {
      get: function() {
        return this.$store.state.locale
      },
      set: function(newVal) {
        this.$store.dispatch('changeLocale', newVal)
      }
    }
  }
 created() {
    i18n.locale = this.lang;
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There you go, we did it!&lt;/p&gt;

&lt;p&gt;We learned how we could implement internationalization in our Vue app with the help of Vue-i18n. The vue-i18n documentation is well written. You will learn about many other translation concepts in the Vue app. We should consider that.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Github Repository: Vue-i18n-tutorial&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/chaymamehrzi/vue-i18n-tutorial.git
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Advanced Features with Vue I18n&lt;/strong&gt;&lt;br&gt;
Vue I18n provides a range of advanced features to handle complex translation requirements. Some of the notable features include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Custom Formatting: You can define custom formatters to format translated values based on your specific requirements.&lt;/li&gt;
&lt;li&gt;Fallback Strategies: Vue internationalization allows you to define fallback strategies for missing translations, ensuring a smooth user experience even when translations are not available.&lt;/li&gt;
&lt;li&gt;Number and Date Formatting: Vue I18n provides built-in support for formatting numbers and dates according to the user's locale.&lt;/li&gt;
&lt;li&gt;Pluralization Rules: You can customize the pluralization rules for different languages, allowing you to handle complex plural forms.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Bonus - How to easily translate your i18n files&lt;/strong&gt;&lt;br&gt;
To learn more about Vue internationalization and its features, refer to the official documentation of Vue.js. Additionally, you can use tools like DevTranslate to automate the translation process and manage your Vue files efficiently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
In this comprehensive guide, we explored the process of Vue internationalization using the Vue I18n plugin.&lt;br&gt;
We hope the tutorial has helped you learn VueI18n and figure out how to get started with your demo app.&lt;/p&gt;

&lt;p&gt;For more such VueJS tutorials, visit the VueJs tutorial page and start digging deeper into the world of Vue.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
