Vue.js is a powerful JavaScript library used for building responsive and interactive user interfaces. Vue is used for its flexibility and simplicity. One of the special features of Vue.js that sets it apart is its plugin system which helps developers extend their Vue application functionality without altering its original behavior.
In this article, we will explore what Vue plugins are, their benefits, how to integrate them into our Vue application, and examine some examples to gain a practical understanding of plugin usage.
Vue.js plugins serve as modular components that extend the functionality of the Vue application without altering its original behavior. They also enable developers to add special features in the form of custom plugins and also add third-party plugins to the Vue app.
Think of plugins as specialized tools you can add to a toolbox with each designed to extend and enhance the functionalities of your Vue application in a modular way.
The way you can include a specific tool for a particular task in your toolbox is the same way Vue plugins add a specific functionality that is tailored to your application's needs.
Imagine you have an application with multiple components, and you need to manage shared data across these components. Though Vue provides built-in features to handle data sharing, handling complex scenarios like this efficiently might require additional tools.
Thereby the need for a plugin that can handle such a task.
Vue plugins can be used to solve a wide range of problems from managing shared data across components to handling complex user interactions. They can also be used to improve the functionality of Vue applications and to optimize the rendering process.
Vue.js plugins help developers solve a wide range of problems faced when building user interfaces. Below, are some examples of third-party plugins.
Vue-select plugin is used for list filtering.
Vuex plugin for state management.
Vue-global for making global libraries available in the Vue application.
Vue-directive for adding global directive in the Vue application.
Now that we have understood the purpose and significance of Vue plugins, let us delve into the syntax for the incorporation of Vue plugins into our applications. Understanding this is very crucial in getting the benefits of plugins in our app.
To use Vue.js third-party plugins, you first need to install it via the package manager npm or yarn. Once installed, you can make use of it in your app by importing it. The example below shows how to use a third-party plugin.
npm install vue-plugin-name
// Import the plugin
import MyPlugin from 'my-plugin';
// Create a Vue instance
const app = createApp(App);
// Use the plugin
app.use(MyPlugin);
// Mount the app
app.mount('#app');
To use custom plugins, when creating custom plugins, you need to define a function that takes the Vue application instance as an argument. This function is where you add the functionality you want your plugin to provide. Below, is a syntax for creating a custom plugin.
// Define the plugin
const MyPlugin = {
install(app, options) {
// Add functionality here
app.config.globalProperties.$myMethod = function() {
// Do something
};
},
};
// Create a Vue instance
const app = createApp(App);
// Use the plugin
app.use(MyPlugin);
// Mount the app
app.mount('#app');
Let's explore some examples of the usage of plugins in Vue. In the example, we are going to look at the different forms of plugins.
In this example, we will use the Vue router plugin used for handling page routing.
/ Step 1: Install Vue Router
npm install vue-router@4
// Step 2: Import and Use Vue Router
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Home from './components/Home.vue'
import About from './components/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes,
})
const app = createApp(App)
app.use(router)
app.mount('#app')
They are personalized components you create in your app depending on your needs. Think of them as solutions you craft out yourself for a specific task.
There are two examples to illustrate how custom plugins are made and applied to our app. The first example is customizing a greeting message while the other one is customizing a modal.
This example defines a Vue.js plugin that utilizes the options parameter and also adds a global method $displayGreeting to the app.
The use of app.config.globalProperties object here is to add global properties or methods to the Vue instance. And this enables the properties or methods to be accessible by any component in the application.
// Define a Vue.js plugin that adds a global method for displaying a greeting message
export default {
install: (app, options) => {
// Add a global method $displayGreeting to the Vue.js application
// This method constructs a greeting message using the provided name and some predefined greeting and ending strings
app.config.globalProperties.$displayGreeting = function(name) {
this.greeting = options.greeting + name + options.ending;
};
},
};
// Create a Vue.js application and use the plugin
import { createApp } from 'vue';
import App from './App.vue';
import DisplayPlugin from './displayPlugin';
const app = createApp(App);
// Use the plugin with options for the greeting and ending strings
app.use(DisplayPlugin, { greeting: 'Welcome to, ', geekstogeeks: '!' });
app.mount('#app');
// Define a Vue.js component that uses the global method to display a greeting message
<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
const name = ref('') // Define a data property for the name
const inputName = ref('') // Define a data property for the input name
onMounted(() => {
// Call the global method when the component is mounted
// Pass the input name as an argument to the method
const instance = getCurrentInstance()
instance?.appContext.config.globalProperties.$displayName(instance, inputName.value)
})
</script>
<template>
<div>
<input type="text" v-model="inputName" placeholder="Enter your name">
<h1>{{ name }}!</h1>
</div>
</template>
In this example, we will explore how to create a custom plugin by creating a simple modal.
Step 1
Create a new file myModal.vue to hold the modal functionalities
//Create the modal component.
<template>
<transition name="modal">
<div class="modal-mask" @click="$emit('close')">
<div class="modal-wrapper" @click.stop>
<div class="modal-container">
<slot></slot>
<button class="modal-default-button" @click="$emit('close')">Close</button>
</div>
</div>
</div>
</transition>
</template>
<style scoped>
.modal-mask {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-container {
background: white;
padding: 20px;
border-radius: 10px;
}
</style>
Step 2
Create the modal plugin
//Create a file modalPlugin.js, to hold your plugin code.
import MyModal from './MyModal.vue';
export default {
install: (app) => {
app.component('my-modal', MyModal);
},
};
Step 3
Use the Plugin in your Application
Javascript//In your main.js file, import the plugin and then apply it to your Vue app.
import { createApp } from 'vue';
import App from './App.vue';
import modalPlugin from './modalPlugin';
const app = createApp(App);
app.use(modalPlugin);
app.mount('#app');
Step 4
Use the modal in your component
Javascript//You can now use the my-modal component in any Vue component.
<template>
<div>
<button @click="showModal = true">Show Modal</button>
<my-modal v-if="showModal" @close="showModal = false">
<h1>Successful!</h1>
<p>You clicked the button.</p>
</my-modal>
</div>
</template>
<script>
export default {
data() {
return {
showModal: false,
};
},
};
</script>
We have looked at what Vue plugins are and their importance in the development process of applications. How their attributes can be beneficial for developers in the building of dynamic and interactive interfaces. Also, we delve into how to create our own required plugins for our apps or choose a suitable one from third-party plugins.
Understanding how to integrate plugins into our app not only makes our work easier as developers but also brings about good practice.
Further reading.