DEV Community

Itachi Uchiha
Itachi Uchiha

Posted on

Registering Components Globally in Vue

Hi, I needed a global component in a Vue.js project. Because I didn't want to import that component each time. I know, this isn't the best approach. But, I needed this one.

Talk is cheap, show me your code! Okay, calm down, let me show you :P

First Step

I created a vue component called spinner.vue.

spinner.vue

<template>
    <b-col cols="12 text-center">
        <i :class="'fa fa-circle-o-notch fa-spin fa-' + size"></i>
        <!-- your other cool stuff -->
    </b-col>
</template>

<script>
export default {
    props: {
        size: {
            type: String,
            default: 'lg'
        }
    }
}
</script>
Enter fullscreen mode Exit fullscreen mode

Now, I have to register the spinner component globally.

Creating Global Component Container

Actually, I don't have any idea about "container". But, I'll say container :P Because all global components will be here. Anyway, I created a file called globalComponents.js under the root folder (src)

import Vue from 'vue'

import spinner from './views/util/spinner.vue'

Vue.component('spinner', 
    () => import('./views/util/spinner.vue')
)
Enter fullscreen mode Exit fullscreen mode

After, I imported globalComponents file from main.js file.

import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
import store from '@/store/store'
import App from './App'
import router from './router'

import '@/globalComponents'
Enter fullscreen mode Exit fullscreen mode

That's all :)

Now, I can use the spinner component in every component.

I hope this will help you. Thanks for reading :)

Discussion (5)

Collapse
lgmaxim31 profile image
lgmaxim31

import Vue from 'vue'

import spinner from './views/util/spinner.vue'

Vue.component('spinner',
() => import('./views/util/spinner.vue')
)
You do not need to import spinner from './views/util/spinner.vue'
Because you import it directly in Vue.component.

Just

import Vue from 'vue'

Vue.component('spinner',
() => import('./views/util/spinner.vue')
)

Collapse
pinedakenneth98 profile image
Kenneth Pineda

How can i call it?

Collapse
itachiuchiha profile image
Itachi Uchiha Author

For example you want to call the spinner component;

<spinner />
Enter fullscreen mode Exit fullscreen mode
Collapse
andrewbogdanovtss profile image
AndrewBogdanovTSS

As usual

Collapse
g33knoob profile image
G33kNoob

How to import multile of it?