Open In App

Vue.js Plugins

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Vue.js is a progressive JavaScript framework used for building user interfaces and single-page applications. Vue.js plugins are reusable and shareable code that can enhance or add functionalities to Vue applications. They help developers to extend the capabilities of Vue by adding global methods, directives, and components which makes code more modular and maintainable.

Think of plugins as power-ups in your favourite video games; they add new abilities and make your game (or in this case, your website) even better. Plugins can help you add cool features like pop-ups, animations, and more without having to write a lot of extra code.

How to Use a Plugin

Using a plugin in Vue.js involves installing the plugin, importing it into your project, and then integrating it into your Vue application. This process generally includes configuring the plugin with any necessary options and using its features in your components.

Installation:

npm install <plugin-name>

Import:

import Plugin from 'plugin-name';
import 'plugin-name/dist/plugin-name.css'; // If the plugin has CSS

Usage:

const options = {
// Plugin-specific options
};

app.use(Plugin, options);

Steps to use Plugin:

Using vue-toastification as an example:

  • Create a New Vue Project
npm create vue@latest
  • Install the plugin
npm install vue-toastification@next
  • In src/main.js, import and use the plugin.
  • Use the Plugin in a Component src/App.vue hat utilizes the plugin's functionality.

Project Structure:

use-plugin
usePlugin Folder Structure

Example: This example shows how to use Plugin.

CSS
/* assets/styles.css */

body {
    font-family: Arial, sans-serif;
    background-color: rgba(0, 0, 0, 0.807);
}

#app {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: aliceblue;
}

button {
    margin-top: 20px;
    background-color: #42b983;
    padding: 10px;
    border-radius: 10%;
    font-weight: bolder;
    cursor: pointer;
    transition: 0.1s ease-in-out;
}

button:hover {
    background-color: #42b983a1;
}
JavaScript
<!-- App.vue -->

<template>
	<div id="app">
		<h1>Use a Plugin - vue-toastification</h1>
		<button @click="showToast">Show Toast</button>
	</div>
</template>

<script>
import { useToast } from 'vue-toastification'

export default {
	name: 'HomePage',
	setup() {
		const toast = useToast()

		const showToast = () => {
			toast.success('Hello, I am a toast message!')
		}

		return { showToast }
	}
}
</script>
JavaScript
// main.js

import { createApp } from 'vue'
import App from './App.vue'
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css'
import './assets/styles.css'

const app = createApp(App)

const options = {
    // Plugin-specific options
}

app.use(Toast, options)

app.mount('#app')

Running the App:

npm run dev

Output: Open your browser and go to http://localhost:8080 to see your Vue application in action.

use-a-plugin-vue-toastification
using a plugin vue-toastification

When the showToast function is called, a small pop-up message will appear on the screen

Writing a Plugin

Creating your own Vue.js plugin allows you to encapsulate functionality that can be reused across multiple projects. This involves defining an install method that takes a Vue constructor and optionally an options object.

Define the plugin:

const MyPlugin = {
install(app, options) {
// Add global method
app.config.globalProperties.$myMethod = function() {
console.log('MyPlugin method');
};

// Add global directive
app.directive('my-directive', {
mounted(el) {
el.style.color = options.color || 'blue';
},
});
},
};

Use the plugin in your Vue app:

import { createApp } from 'vue';
import App from './App.vue';
import MyPlugin from './path-to-my-plugin';

const app = createApp(App);
app.use(MyPlugin, { color: 'red' });
app.mount('#app');

Steps to create a Plugin

Creating a simple plugin that changes the text color of an element:

  • Create a New Vue Project
npm create vue@latest
  • Create a new file src/plugins/ColorPlugin.js.
  • Writing the Plugin , by Implement the custom plugin logic.
  • Import the Plugin in src/main.js and then use the custom plugin.
  • Use the Plugin in a src/App.vue that uses the custom plugin's features.

Folder Structure

write-plugin
writePlugin Folder Structure

Example: This example shows the creation of plugin.

HTML
<!-- App.vue -->

<template>
  <div id="app">
    <h1 v-color>Writing a Plugin - ColorPlugin</h1>
  </div>
</template>
CSS
/*  assets/styles.css */

body {
  font-family: Arial, sans-serif;
  background-color: rgba(0, 0, 0, 0.807);
}


#app{
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: aliceblue;
}
JavaScript
// main.js

import { createApp } from "vue";
import App from "./App.vue";
import ColorPlugin from "./plugins/ColorPlugin";
import "./assets/styles.css";

const app = createApp(App);

app.use(ColorPlugin, { color: "green" });

app.mount("#app");
JavaScript
// plugins/ColorPlugin.js

const ColorPlugin = {
  install(app, options) {
    app.directive("color", {
      mounted(el) {
        el.style.color = options.color || "black";
      },
    });
  },
};

export default ColorPlugin;

Running the App:

npm run dev

Output: Open your browser and go to http://localhost:8080 to see your Vue application in action.

writing-a-plugin
This text will appear in green color

Inject with Plugin

Injecting properties or methods with plugins allows them to be accessible in all Vue components without the need to import them each time. This is typically done by adding properties to the global properties of the Vue app instance.

Define the plugin with injection:

const InjectPlugin = {
install(app, options) {
app.config.globalProperties.$myInjectedFunction = () => {
console.log('This is an injected function');
};
},
};

Use the plugin in your Vue app:

import { createApp } from 'vue';
import App from './App.vue';
import InjectPlugin from './inject-plugin';

const app = createApp(App);
app.use(InjectPlugin);
app.mount('#app');

Example of usage in a component:

<template>
<div>
<button @click="useInjectedFunction">Click me</button>
</div>
</template>

<script>
export default {
methods: {
useInjectedFunction() {
this.$myInjectedFunction();
},
},
};
</script>

Steps to inject Plugin in the Project:

Creating a simple plugin that injects a function:

  • Create a New Vue Project
npm create vue@latest 
  • Create a new file src/plugins/MessagePlugin.js.
  • Write the injection logic in MessagePlugin.js.
  • Inject the Plugin into Vue Instance through src/main.js, import and use the injection plugin.
  • Use the Injected Functionality in src/App.vue that calls the injected functionality.

Project Structure:

Inject-Plugin
injectPlugin Folder Structure

Example: This example shows the inject with plugin.

HTML
<!-- App.vue -->

<template>
	<div id="app">
		<h1>Inject with Plugin - MessagePlugin</h1>
		<button @click="$showMessage">Show Message</button>
	</div>
</template>

<script>
export default {
	name: 'App',
};
</script>
CSS
/* assets/styles.css */

body {
    font-family: Arial, sans-serif;
    background-color: rgba(0, 0, 0, 0.807);
}


#app {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: aliceblue;
}

button {
    margin-top: 20px;
    background-color: #42b983;
    padding: 10px;
    border-radius: 10%;
    font-weight: bolder;
    cursor: pointer;
    transition: 0.1s ease-in-out;
}

button:hover {
    background-color: #42b983a1;
}
JavaScript
// main.js

import { createApp } from "vue";
import App from "./App.vue";
import MessagePlugin from "./plugins/MessagePlugin";
import "./assets/styles.css";

const app = createApp(App);

app.use(MessagePlugin);

app.mount("#app");
JavaScript
// plugins/MessagePlugin.js

const MessagePlugin = {
	install(app) {
		app.config.globalProperties.$showMessage = () => {
			alert("Hello from the injected function!");
		};
	},
};

export default MessagePlugin;

Running the App:

npm run dev

Output: Open your browser and go to http://localhost:8080 to see your Vue application in action.

inject-with-plugin

When the button is clicked, an alert with the message "Hello from the injected function!" will be displayed.


Next Article

Similar Reads