adbrosaci / vue-lang-router

Vue language routing with (optional) localized URLs.
MIT License
66 stars 8 forks source link

Add support for locale info in component #1

Closed andrejilderda closed 4 years ago

andrejilderda commented 4 years ago

Hi @radek-altof, thanks for this very well-featured plugin! One thing of Vue I18n I'm missing though is the ability to add locale info to components, so that you can add translations in the component in stead of a dedicated json-file. Like so:

<i18n>
    {
        "en": {
            "heading": "About us"
        },
        "nl": {
            "heading": "Over ons"
        }
    }
</i18n>

https://kazupon.github.io/vue-i18n/guide/component.html#shared-locale-messages-for-components

radek-altof commented 4 years ago

Hey @ajilderda , I'll take a look at it and see if it's possible to implement into the plugin. Thanks for the feedback :)

radek-altof commented 4 years ago

Hey @ajilderda, I tried to reproduce your issue, but everything seems to work fine. Are you sure you configured everything properly?

I created the following component and the messages load correctly.

<template>
  <div>
    <p>{{ $t('hello') }}</p>
    <p>{{ $t('msg') }}</p>
  </div>
</template>

<script>
export default {
  i18n: {
    messages: {
      en: {
        hello: 'Hello!',
      },
      cs: {
        hello: 'Ahoj!',
      },
    },
    sharedMessages: {
      en: {
        msg: 'This is a shared message.',
      },
      cs: {
        msg: 'Tohle je sdílená zpráva.',
      },
    },
  },
};
</script>

If you want to use <i18n> tag inside SFCs, please take a look at the documentation here. You need to install vue-i18n-loader and then modify webpack configuration, in order to load those messages.

After doing so, the following SFC should work properly, i18n will refer to the globally set locale.

<i18n>
{
  "en": {
    "hello": "Hello!"
  },
  "cs": {
    "hello": "Ahoj!"
  }
}
</i18n>

<template>
  <div>{{ $t('hello') }}</div>
</template>

If you don't want to have any global messages whatsoever, you can modify the load function inside your translations config to return an empty promise. This will setup the languages, but won't load any global messages. You'll then need to specify your messages inside your components, of course.

/* router/index.js */

Vue.use(LangRouter, {
  defaultLanguage: 'en',
  translations: {
    en: {
      name: 'English',
      load: () => { return Promise.resolve({}); },
    },
    cs: {
      name: 'Česky',
      load: () => { return Promise.resolve({}); },
    },
  },
  localizedURLs,
});

Let me know if this helps. In case there's still an issue, please post some example code.

andrejilderda commented 4 years ago

My bad, I skipped the vue-i18n-loader-part. It works like a charm. ✨ Thanks!