Thursday, 21 December 2023

Laravel + Inertia + Vue3 + Typescript add plugin multi languages vue-i18n

1. Install package i18n

npm install vue-i18n

2. Add files languages

 resources\lang\en.json

{
    "world": "HELLO EN"
}

 resources\lang\vi.json

{
    "world": "HELLO VI"
}

3. Add plugin resources\js\plugins\langPlugin.ts

import { App } from 'vue';
import { createI18n, type I18nOptions } from 'vue-i18n';
import en from '../../lang/en.json';
import vi from '../../lang/vi.json';

const langPlugin = {
install(app: App, pluginOptions: any) {
const langOptions: I18nOptions = {
legacy: false,
locale: pluginOptions.locale ? pluginOptions.locale : 'en',
messages: {
en: en,
vi: vi,
},
};
const i18n = createI18n(langOptions);
app.use(i18n);
console.log(app);
},
};

export default langPlugin;

* need: legacy: false, see more >>

4. Update resources\js\app.ts

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob<DefineComponent>('./Pages/**/*.vue')),
    setup({ el, App, props, plugin }) {
        createApp({ render: () => h(App, props) })
            .use(plugin)
            .use(ZiggyVue)
            .use(langPlugin, {})
            .mount(el);
    },
    progress: {
        color: '#4B5563',
    },
});

5. Using I18n

- In template

   {{ $t('world') }}

- in <script setup>

import { useI18n } from 'vue-i18n';
const { t } = useI18n();
console.log(t('hello'));

Thank you

No comments:

Post a Comment

Golang Advanced Interview Q&A