Access Vue3 global components

Viewed 1141

So I'm trying to convert this Vue2 project to Vue3(typescript).

It's registering components globally and accessing them to match against a value in my store, however when trying to implement this in Vue3 the components stay undefined.

import getComponentTypeForContent from "../api/getComponentTypeForContent";
import { mapState } from "vuex";
import { defineComponent } from "vue";

export default defineComponent({
  name: "PageComponentSelector",
  beforeCreate: function () {
    console.log("CREATED PAGECOMPONENTSELECTOR");
  },
  computed: mapState({
    model: (state) => state.epiDataModel.model,
    modelLoaded: (state) => state.epiDataModel.modelLoaded,
  }),
  methods: {
    getComponentTypeForPage(model) {
      // this.$options.components will contain all globally registered components from main.js
      return getComponentTypeForContent(model, this.$options.components);
      // this.$options.components fetches all components for vue2 app
    },
  },
});

and registering components like this:

//Pages
import LoginPage from "./components/pages/Login.vue";

const appAdv = createApp(App);

//Register components
appAdv.component("LoginPage", LoginPage);

appAdv.use(store).use(router).mount("#appAdv");

Can't find (or searching badly) how to do this or similar in vue3 so I've come here hoping someone could help hehe

1 Answers

I also frequently use parent components in child components, but don't (or haven't) used the App.component method

In vue3 I usually use the provide/inject . method

Provide

const app = createApp(App);
app.provide('someVarName', someVar);  // `Provide` a variable to all components here

Inject:

// In *any* component
const { inject } = Vue;
...
setup() {
  const someVar = inject('someVarName');   // injecting variable in setup

  return {someVar}
}
Related