The way plugins are coded in Vue.js 3 with Composition API differ from traditional plugins. Traditional are used via a install function and added using Vue.use(plugin). They usually manipulate/extend the Vue prototype.

However, in Composition API plugins are non-manipulative and coded using an inject-provide pattern. For instance, you can create a i18n plugin like this:

// i18nPlugin.js
import { ref, provide, inject } from "@vue/composition-api";

const createI18n = config => ({
  locale: ref(config.locale),
  messages: config.messages,
  $t(key) {
    return this.messages[this.locale.value][key];
  }
});

const i18nSymbol = Symbol();

export function provideI18n(i18nConfig) {
  const i18n = createI18n(i18nConfig);
  provide(i18nSymbol, i18n);
}

export function useI18n() {
  const i18n = inject(i18nSymbol);
  if (!i18n) throw new Error("No i18n provided!!!");

  return i18n;
}

As you can see, the functions provide and inject are used to create the plugin instance and hold it in a dependency injection mechanism.

Check that we use ref for the locales, since we need the to be reactive.

If you’re not very familiar yet with Composition API, please read the tip to easily migrate to Composition API and how to use old instance properties to get a bit more in detail about it.

Then, once in the app you must initialize the plugin with the right configuration by using the provideI18n function. That’s usually done in the root App.vue component:

<script>
  import { provideI18n } from "./i18nPlugin";
  import HelloWorld from "./HelloWorld";

  export default {
    components: { HelloWorld },
    setup() {
      provideI18n({
        locale: "en",
        messages: {
          en: {
            hello_world: "Hello world"
          },
          es: {
            hello_world: "Hola mundo"
          }
        }
      });
    }
  };
</script>

#vue #vue.js #vue.js 3 #api #i18n

Create a i18n Plugin with Composition API in Vue.js 3
65.10 GEEK