Creating a simple plugin
A plugin for Vue.js is a JavaScript object you can add functionality to your instance of Vue, or extend it into the Vue ecosystem. Global components, directives, mixins, example methods, and many others can be part of plugins.
Syntax:
const myPlugin = {
install(app) {
app.config.globalProperties.$customMethod = function (message) {
alert(`Hello ${message}! Thanks for clicking.`);
};
},
};
Example: Below example demonstrates the creation of a simple plugin.
myPlugin.js
Javascript
const myPlugin = { install(app) { app.config.globalProperties.$customMethod = function (message) { alert(`Hello ${message}! Thanks for clicking.`); }; }, }; export default myPlugin; |
main.js
Javascript
import { createApp } from 'vue' ; import App from './App.vue' ; import myPlugin from '../src/plugins/myPlugin' ; const app = createApp(App); app.use(myPlugin); app.mount( '#app' ); |
App.vue
Javascript
<template> <div> <h1>w3wiki</h1> <h2 style= "color: green" > Plugins in Vue.js </h2> <button @click= "pluginMsg" >click</button> </div> </template> <script> export default { methods: { pluginMsg() { this .$customMethod( "w3wiki" ); }, }, }; </script> |
Output:
Explain Plugins in Vue.js
VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer, it is easy to pick up for any developers. It is compatible with other libraries and extensions as well. If you want to create a single-page application, I think VueJS is the first choice.
In this article, we will learn what plugins are in Vue.js. We will also see different approaches to implement them, along with their respective syntaxes and complete examples.
Contact Us