To handle localization in a Vue.js project using Inertia.js, you can use the vue-i18n library, which is a popular internationalization plugin for Vue.js. Here’s a step-by-step guide to set it up:
-
Install
vue-i18n: First, you need to install thevue-i18npackage. You can do this using npm or yarn.npm install vue-i18n # or yarn add vue-i18n -
Set up
vue-i18nin your Vue project: Create a localization setup file, for example,i18n.js, and configure your languages.// src/i18n.js import { createI18n } from 'vue-i18n'; // Import your language files import en from './locales/en.json'; import fr from './locales/fr.json'; const messages = { en, fr, }; const i18n = createI18n({ locale: 'en', // set locale fallbackLocale: 'en', // set fallback locale messages, // set locale messages }); export default i18n; -
Integrate
vue-i18nwith your Vue app: Modify your main entry file to use thei18ninstance.// src/main.js import { createApp } from 'vue'; import { createInertiaApp } from '@inertiajs/inertia-vue3'; import i18n from './i18n'; createInertiaApp({ resolve: name => require(`./Pages/${name}`), setup({ el, App, props, plugin }) { createApp({ render: () => h(App, props) }) .use(plugin) .use(i18n) .mount(el); }, }); -
Create your language files: Create JSON files for each language in a
localesdirectory.// src/locales/en.json { "welcome": "Welcome", "hello": "Hello" }// src/locales/fr.json { "welcome": "Bienvenue", "hello": "Bonjour" } -
Use the
tfunction in your Vue components: Now you can use the$tfunction provided byvue-i18nto translate your text.<template> <div> <p>{{ $t('welcome') }}</p> <p>{{ $t('hello') }}</p> </div> </template> <script> export default { name: 'ExampleComponent', }; </script> -
Switching languages: You can switch languages by changing the
localeproperty of thei18ninstance.<template> <div> <button @click="changeLanguage('en')">English</button> <button @click="changeLanguage('fr')">Français</button> </div> </template> <script> export default { methods: { changeLanguage(lang) { this.$i18n.locale = lang; }, }, }; </script>
By following these steps, you should be able to set up localization in your Vue.js project using Inertia.js and vue-i18n. This will allow you to easily manage and switch between multiple languages in your application.