🟢 Handling I18N in Vue
The basic usage of this plugin is really straightforward. If you would like to see more, checkout official documentation https://vue-i18n.intlify.dev/.
First we need to install it using our favourite package manager (in my case it is yarn):
yarn add vue-i18n@9
Next, we need to create I18N plugin and configure our Vue app to use it like following:
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
// options
})
const app = createApp({
// options
})
app.use(i18n)
app.mount('#app')
This would register the I18N plugin but in order to actually make it work the way we want, we need to pass some configuration options:
const i18n = VueI18n.createI18n({
locale: 'pl',
fallbackLocale: 'en',
messages: {
en: {
message: {
hello: 'Hello'
}
},
pl: {
message: {
hello: 'Cześć'
}
}
}
})
And then, when we use following code in our template we should see translated text:
<div id="app">
<p>{{ $t("message.hello") }}</p>
</div>
>>>
<div id="app">
<p>Cześć</p>
</div>
And that's it for the basic usage. For more advanced concepts check out https://vue-i18n.intlify.dev/guide/essentials/syntax.html
🟢 Handling I18N in Nuxt
The usage for Nuxt is very similar, first we need to install the module:
yarn add -D @nuxtjs/i18n
Next, add it to the modules array in nuxt.config.ts file:
export default defineNuxtConfig({
modules: ['@nuxtjs/i18n']
})
And provide all required configuration:
export default defineNuxtConfig({
modules: ['@nuxtjs/i18n'],
i18n: {
legacy: false,
locale: 'en',
messages: {
en: {
welcome: 'Welcome'
},
fr: {
welcome: 'Bienvenue'
}
}
}
})
And we can use it in the application like following:
<script setup>
const { locale, setLocale } = useI18n()
</script>
<template>
<div>
<div>
<button @click="setLocale('en')">en</button>
<button @click="setLocale('fr')">fr</button>
<p>{{ $t('welcome') }}</p>
</div>
</div>
</template>
For more, check out https://i18n.nuxtjs.org/
📖 Learn more
If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:
Vue School Link
It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉
✅ Summary
Well done! You have just learned how to utilize internationalization (I18N) in Vue applications.
Take care and see you next time!
And happy coding as always 🖥️