vue-i18n-composable icon indicating copy to clipboard operation
vue-i18n-composable copied to clipboard

Use of i18nInstance in useI18n

Open duebbert opened this issue 3 years ago • 1 comments

I ran into issues when using createI18n and then useI18n (most likely something due to my vue-cli webpack setup). But it made me wonder why you are using the i18nInstance from createI18n?

I slightly amended the useI18n code to use the $i18n instance that is on the current Vue instance instead:

function useI18n() {
  const instance = getCurrentInstance();
  const vm = (instance == null ? void 0 : instance.proxy) || instance || new Vue({});

  const i18n = vm.$i18n;
  if (!i18n)
    throw new Error("vue-i18n not initialized");

  const locale = computed({
    get() {
      return i18n.locale;
    },
    set(v) {
      i18n.locale = v;
    }
  });
  return {
    locale,
    t: vm.$t.bind(vm),
    tc: vm.$tc.bind(vm),
    d: vm.$d.bind(vm),
    te: vm.$te.bind(vm),
    n: vm.$n.bind(vm)
  };
}

This way vue-i18n can be instantiated as usual and createI18n isn't needed (but could still be used). In the component you just use useI18n.

I might be missing something but wouldn't this make the code much easier to use?

duebbert avatar Sep 12 '22 15:09 duebbert

Bet this would fix the complications I'm having sharing i18n between vue cli and nuxt builds.

gavmck avatar Nov 04 '22 14:11 gavmck