How to Create Handy Global Vue Components

May 15 2018 | By Taha Shashtari

There are some components that your app would need to have a single instance of. These components should only be created once and accessed directly from anywhere you want. For this type of component, it's unnecessary to import it and create a new instance of it each time we need to use it.

For example, showing a progress bar at the top of the page when switching between pages should be done simply by calling this.$bar.show() and this.$bar.finish() from any component in our app.

Another example is displaying a tooltip when the mouse hovers over some element. We should easily display it by calling this.$tooltip.show('your message', nodeElementToPointAt). And it should be closed using something like this.$tooltip.hide().

I think these examples are enough to get you motivated. Now let's see how it's done.

Let's see a quick example

Let's take the tooltip example. First, you have to create that component in your components directory. Let's name it Tooltip.vue, for example.

<template>
  <div class="tooltip"></div>
</template>

<script>
export default {
  methods: {
    show (msg, el) {
      console.log('show the tooltip')
    },

    hide () {
      console.log('hide the tooltip')
    }
  }
}
</script>

Now let's expose it globally from main.js.

// Import it first
import Tooltip from '@/components/Tooltip'

// Add a new instance of it to Vue.prototype
const tooltip = Vue.prototype.$tooltip = new Vue(Tooltip).$mount()
// Display the component in body
document.body.appendChild(tooltip.$el)

You should now be able to access this component from anywhere using this.$tooltip.

My last note on this is that it's better to have some naming convention for your global components to avoid conflicts with other component's local data. In our case, we prefixed the name with $.