Import all ionic components into a Ionic-Vue view

1.5k Views Asked by At

I'm building a Ionic-Vue 5 mobile app and I'm finding myself import a lot of vue components just to use them into my views:

import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonInput,
  IonButton,
  IonAlert,
  IonList,
  IonItem,
  IonCard,
  IonCardContent,
  IonCardHeader,
  IonCardSubtitle,
  IonLabel,
  IonSpinner
} from "@ionic/vue";

export default defineComponent({
  components: {
    IonHeader,
    IonToolbar,
    IonTitle,
    IonContent,
    IonPage,
    IonInput,
    IonButton,
    IonAlert,
    IonList,
    IonItem,
    IonCard,
    IonCardContent,
    IonCardHeader,
    IonCardSubtitle,
    IonLabel,
    IonSpinner
  },

I know this could be useful from a performance point of view, but there is a way to just import all ionic components at once when the list is big enough to justify a little performance loss in order to greatly simplify the code?

2

There are 2 best solutions below

1
On BEST ANSWER

In main.js (or wherever you create your Vue app):

import * as IonComponents from '@ionic/vue';

Object.keys(IonComponents).forEach(key => {
    if (/^Ion[A-Z]\w+$/.test(key)) {
        app.component(key, IonComponents[key]);
    }
});

If it's before you've created your Vue app, just swap in Vue.component(…) in place of app.component(…).

The regex ensures that only the components get registered as components, they all start with Ion. The other items in that import are mostly functions, which you'll need to import when needed.

0
On

You can always do something like app.component('ion-app', IonApp) in your main.js after you have initialized the app variable.

By doing so, you are basically importing all the components once and making those available to all the components.

Now you can directly use <ion-app>...</ion-app> in your templates without importing the ionic components everytime.