Table of contents
1.
Introduction
2.
What are Plugins and their uses?
3.
Making custom plugins to make our component global
4.
Reusing components globally using plugins
5.
Making global Directives
6.
The options argument of install method
7.
Creating global mixins using plugins
8.
FAQs
9.
Key Takeaways
Last Updated: Mar 27, 2024

Plugins in Vue.js

Author Toohina Barua
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We decorate our homes with many fairy lights during festival season and occasions. Connecting every fairy light string to the sockets and switching it on and off, again and again, would be a very tedious task. So, we connect all the lights to an extension board and plugin once, and all of them light up! Moreover, we don’t have to use up all the sockets at our home, an additional benefit! Similarly, when using plugins in Vue.js, we can use elements globally without making and importing them again and again.

Source

As coders, we all want to do smart work that requires as little effort as possible. Plugins are a great way to make writing code easier by providing global functionalities, reusability, and additional features to our App!

What are Plugins and their uses?

Plugins are add-ons to our App that provide additional functionalities and capabilities. In Vue, they help us add global components and features to our App. Once you make your plugin, you don’t have to worry about importing it again and again in different app components as it becomes available globally throughout the entire App. Given below is a list of areas where plugins are helpful:

  • Making global Vue DOM components
  • Making global directives
  • Making global mixins
  • Making global properties and instance methods by attaching them to app.config.globalProperties


We will look at some of the above through practical examples.

Making custom plugins to make our component global

There are a lot of useful plugins available made by other developers like Vue Lazyload, Vue Notification, Vue Router, Vue Custom Element, Vue Touch, etc. Just add these plugins to your code, and you are ready to go! However, we may sometimes want functionalities that are unique to our needs. For times like these, we can make our very own plugin! 

Run the following command in the terminal to create your Vue project named plugins-demo:

vue create plugins-demo

Go into the plugins-demo directory using the cd command and run the following command to start your App at localhost:8080 :

npm run serve

Delete the HelloWorld.vue and make the following files so that your initial file structure looks like the figure given below.

  • Make a CustomPlugin.js file in the src folder. (Note: CustomPlugin is a javascript file)
  • Make GlobalIntro.vue and Mid.vue inside the components folder.

GlobalIntro.vue

This file will contain the code of the component we will make global. Slots are the part of the code that can be changed from other components by accessing it using the name attribute. We have also added styling to this global component inside the style tags. 

<template>

    <div id="global-component">

        <h2><slot name="intro-heading"/></h2>

        <p><slot name="intro-body"/></p>

    </div>

</template>

<style>

#global-component{

    border: 3px solid purple;

    margin:0 30%;

}

</style>

CustomPlugin.js 

To make GlobalIntro.vue component global, we first have to import it to CustomPlugin.js. The install method is called wherever we want our plugin. The install method takes two parameters: 1) the app object returned by the createApp function and 2) the options given by us.  We can access the GlobalIntro.vue component by the name global-intro from anywhere in the App.

import GlobalIntro from "./components/GlobalIntro"

export default {

    install: (appoptions) => {

        app.component("global-intro"GlobalIntro)

    }

}

main.js

We will import CustomPlugin.js file in main.js and then use it in the app.

import { createApp } from 'vue'

import App from './App.vue'

import CustomPlugin from './CustomPlugin'

const app = createApp(App)

app.use(CustomPlugin)

app.mount('#app')

App.vue

Now we can add the GlobalIntro.vue to the App.vue file without importing and registering it in the components. 

<template>

 <h1>Plugins in Vue</h1>

 <global-intro>

   <template #intro-heading>

     Global Component

   </template>

   <template #intro-body>

     We can make global components by making custom plugins.

   </template>

 </global-intro>

</template>

 

<script>

export default {

  name: 'App',

}

</script>

 

<style>

#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;

  text-align: center;

  color: #2c3e50;

}

</style>

localhost:8080

Reusing components globally using plugins

We can even reuse GlobalIntro.vue inside many components simultaneously. The styles of the global component can be overwritten by the components in which we are using it. Let us see its demonstration:

Mid.vue

<template>

    <div id="mid">

        <global-intro>

        <template #intro-heading>

            Reusability

        </template>

        <template #intro-body>

            Reusing the GlobalIntro.vue in Mid.vue with the help of plugin. Now we don't have to write the same code again and again!

        </template>

        </global-intro>

    </div>

</template>

<script>

export default{

    name:"Mid"

}

</script>

<style>

#mid{

    background-color:rgb(241, 204, 217);

    margin:20px 0;

    padding:20px 0;

}

</style>

localhost:8080

Making global Directives

Directives like v-if, v-show, v-bind, etc., can change the Vue App DOM on the go. We can make our very own global directive using plugins. Let us see how we can do this:

CustomPlugin.js

We can create the directive using app.directive() method. This custom directive will change the background and font-color of the elements it is used on.

import GlobalIntro from "./components/GlobalIntro"

export default {

    install: (appoptions) => {

        app.component("global-intro"GlobalIntro)

        app.directive("global-color"(elbindingvnode) => {

            var backgroundColor = "white"

            var color = "black"

            if (binding.arg == "color1") {

                backgroundColor = "powderblue"

                color = "purple"

            } else if (binding.arg == "color2") {

                backgroundColor = "#FF3659"

                color = "white"

            } else {

                backgroundColor = "white"

                color = "black"

            }

            el.style.backgroundColor = backgroundColor;

            el.style.color = color;

        })

    }

}

Mid.vue

Now, we can use the directive we made, globally. We can also use the directive on the global components we had made earlier! 

<template>

    <div>

        <div id="mid">

            <global-intro v-global-color:color2>

            <template #intro-heading>

                Reusability

            </template>

            <template #intro-body>

                Reusing the GlobalIntro.vue in Mid.vue with the help of plugin. Now we don't have to write the same code again and again!

            </template>

            </global-intro>

        </div>

        <div class="directive-div" v-global-color:color1>

            <h2>Div 1</h2>

        </div>

        <div class="directive-div" v-global-color:color2>

             <h2>Div 2</h2>

        </div>

    </div>

</template>

<script>

export default{

    name:"Mid"

}

</script>

<style>

#mid{

    background-color:rgb(241, 204, 217);

    margin:20px 0;

    padding:20px 0;

}

.directive-div{

    padding:20px 0;

}

</style>

localhost:8080

The options argument of install method

As we saw earlier, the install method has an argument, namely options that take values from the user. Using this, we can pass values of our choice to influence the DOM instead of hardcoding it. Let us have a look at it. We will modify the above code for directives.

main.js

The custom values for options is passed through the app.use() method. Let us pass our object for the directive we had written earlier.

import { createApp } from 'vue'

import App from './App.vue'

import CustomPlugin from './CustomPlugin'

const app = createApp(App)

app.use(CustomPlugin, {

    colorObj: {

        color1: {

            bg: "grey",

            f: "white"

        },

        color2: {

            bg: "powderblue",

            f: "teal"

        }

    }

})

app.mount('#app')

CustomPlugin.js

import GlobalIntro from "./components/GlobalIntro"

export default {

    install: (appoptions) => {

        app.component("global-intro"GlobalIntro)

        app.directive("global-color"(elbindingvnode) => {

            var backgroundColor = "white"

            var color = "black"

            if (binding.arg == "color1") {

                backgroundColor = options.colorObj.color1.bg

                color = options.colorObj.color1.f

            } else if (binding.arg == "color2") {

                backgroundColor = options.colorObj.color2.bg

                color = options.colorObj.color2.f

            } else {

                backgroundColor = "white"

                color = "black"

            }

            el.style.backgroundColor = backgroundColor;

            el.style.color = color;

        })

    }

}

localhost:8080

Creating global mixins using plugins

We know that mixins are used to reuse a part of code. However, whenever we want to use a mixin in a Vue component file, we have to import it and put it inside the mixin array each and every time. We can avoid this altogether by making a global plugin for the mixin. Let us see this in practice:

CustomPlugin.js

Let’s make a mixin using app.mixin() function.

import GlobalIntro from "./components/GlobalIntro"

export default {

    install: (appoptions) => {

        app.component("global-intro"GlobalIntro)

        app.directive("global-color"(elbindingvnode) => {

            var backgroundColor = "white"

            var color = "black"

            if (binding.arg == "color1") {

                backgroundColor = options.colorObj.color1.bg

                color = options.colorObj.color1.f

            } else if (binding.arg == "color2") {

                backgroundColor = options.colorObj.color2.bg

                color = options.colorObj.color2.f

            } else {

                backgroundColor = "white"

                color = "black"

            }

            el.style.backgroundColor = backgroundColor;

            el.style.color = color;

        })

        app.mixin({

            data() {

                return {

                    count: 0

                }

            },

            methods: {

                increaseCount() {

                    this.count++

                }

            }

        })

    }

}

Make a file named Button.vue inside the components folder. We will make a Button component with a button and an h3 that displays the number of times the button has been clicked. We will use the global mixin here that we made in the CustomPlugin.js file.

Button.vue (inside components folder)

<template>

    <div>

        <button @click="increaseCount">Click Me</button>

        <h3>The button has been clicked {{count}} times</h3>

    </div>

</template>

<script>

export default{

    name:"Button",

}

</script>

<style>

button{

    margin:15px 0;

    border:none;

    border-radius:5px;

    background-color:teal;

    color:white;

    padding:15px;

    box-shadow: 5px 5px 10px grey;

    font-size:25px;

}

button:hover{

    box-shadow: none;

}

</style>

App.vue

Import the button component inside App.vue.

<template>

 <h1>Plugins in Vue</h1>

 <global-intro>

   <template #intro-heading>

     Global Component

   </template>

   <template #intro-body>

     We can make global components by making custom plugins.

   </template>

 </global-intro>

 <Mid/>

 <Button/>

</template>

<script>

import Button from "./components/Button.vue"

import Mid from "./components/Mid.vue";

export default {

  name: 'App',

  components:{

    Mid,

    Button

  }

}

</script>

<style>

#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;

  text-align: center;

  color: #2c3e50;

}

</style>

localhost:8080

FAQs

  1. What are the disadvantages of Plugins made by other developers?
    Ans. Using Plugins made by other developers might make our App vulnerable to security issues. When we use different plugins from different developers, they may not work correctly together. Old plugins may not be updated by their developers, which may cause problems in our code.
     
  2. How can we make functions/methods and properties global using plugins?
    Ans. We can use the provide/inject pattern to make functions and properties available to all components globally using plugins.
     
  3. What is the difference between instance and global methods in Vue? When to use what?
    Ans. An instance method will operate on an instance (this). The instance can be any component. A global function would have Vue itself as its instance(this). Thus, use the instance method if you want to operate on the instance of a component. Use the global method to achieve functionality that doesn't operate on a Vue instance. Although, using either of them, in any case, won’t be wrong. 

Key Takeaways

We learned what plugins are, why they are used, and how to use them from this article. We also saw a  few practical examples where using plugins in different ways is beneficial. Vue Plugins are a vast topic, so stay tuned with us to know more. If you want to learn more about Vue.js, you can read our articles on Vue.js or take our highly curated Web Development course.

Live masterclass