Open In App

How to Create Custom VueJS Plugins ?

Vue.js is a frontend javascript framework that is used to create web apps and single-page applications. It follows the pattern of creating and using components as the building blocks for the application. Vue.js plugins are the reusable pieces of code, that allow us to abstract out and encapsulate the logic, and then use those across different components.

Steps to create custom Vue.js plugin

Step 1: Create a Vue application

First, create a Vue.js application with the below command:



vue create plugins

Project structure:

Step 2: Create a plugins folder

Create a plugins folder inside the “src” directory, and create a “customPlugin.js” file there. In our custom plugin, we will just print, “This is from custom plugin” statement to the console whenever the plugin is used.

Filename: customPlugin.js



const CustomPlugin = {
install(Vue) {
Vue.mixin({
created() {
console.log("Hello from my Vue plugin");
},
});
},
};

export default CustomPlugin

Step 3: Import and use the plugin in main.js file

Now, let’s import and use the plugin in main.js file, and see if we can view the console logs getting printed by our custom plugin component. We will use “Vue.use()” in order to use the plugin.

Filename: main.js

import { createApp } from 'vue'
import App from './App.vue'
import CustomPlugin from './plugins/customPlugin'

const app = createApp(App)

app.use(CustomPlugin)

app.mount('#app')

Now, let’s run the above code with the command given below to see the output:

pnpm serve

Output:

Article Tags :