loading...

Registering Components Globally in Vue

aligoren profile image Ali GOREN ・1 min read

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>

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')
)

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'

That's all :)

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

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

Posted on by:

aligoren profile

Ali GOREN

@aligoren

I'm a front-end developer. I'm living in Turkey. I started my professional career in 2016. I also interest in Backend, SQL technologies.

Discussion

markdown guide
 

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')
)

 
 

For example you want to call the spinner component;

<spinner />
 

How to import multile of it?