vue.js logo

Creating plugins in Vue.js


Step 1: Create a Plugin

Let's create a simple plugin that provides a global method to format dates.

1. Create a plugin file: `src/plugins/myPlugin.js`



                // src/plugins/myPlugin.js

export default {
  install(app, options) {
    // Adding a global method
    app.config.globalProperties.$formatDate = function (dateStr) {
      const options = { year: 'numeric', month: 'long', day: 'numeric' };
      return new Date(dateStr).toLocaleDateString(undefined, options);
    };
  }
};

Step 2: Register the Plugin

You need to register the plugin with your Vue app. This is typically done in the main entry file of your application.

1. Update main.js:



          import { createApp } from 'vue';
          import App from './App.vue';
          import myPlugin from './plugins/myPlugin';

          const app = createApp(App);

          // Register the plugin
          app.use(myPlugin);

          app.mount('#app');

Step 3: Use the Plugin

Now you can use the global method provided by your plugin anywhere in your Vue components.

1. Update a component to use the plugin method: `src/components/MyComponent.vue`



          <template>
            <div>
              <p>Original Date: {{ date }}</p>
              <p>Formatted Date: {{ formattedDate }}</p>
            </div>
          </template>

          <script>
          export default {
            data() {
              return {
                date: '2024-07-16'
              };
            },
            computed: {
              formattedDate() {
                return this.$formatDate(this.date);
              }
            }
          };
          </script>

Advanced Example: HTTP Client Plugin

Here’s a more advanced example of a plugin that wraps an HTTP client like Axios.

1. Create the plugin file: src/plugins/httpClient.js



          // src/plugins/httpClient.js
          import axios from 'axios';

          export default {
            install(app, options) {
              // Create an Axios instance
              const axiosInstance = axios.create({
                baseURL: options.baseURL,
                headers: options.headers
              });

              // Adding a global method to make HTTP requests
              app.config.globalProperties.$http = axiosInstance;
            }
          };

2. Register the plugin with options: Update main.js



          import { createApp } from 'vue';
          import App from './App.vue';
          import httpClient from './plugins/httpClient';

          const app = createApp(App);

          // Register the HTTP client plugin with options
          app.use(httpClient, {
            baseURL: 'https://api.example.com',
            headers: {
              'Authorization': 'Bearer your-token'
            }
          });

          app.mount('#app');

Use the HTTP client in a component: `src/components/ApiComponent.vue`



          <template>
            <div>
              <button @click="fetchData">Fetch Data</button>
              <pre>{{ data }}</pre>
            </div>
          </template>

          <script>
          export default {
            data() {
              return {
                data: null
              };
            },
            methods: {
              async fetchData() {
                try {
                  const response = await this.$http.get('/endpoint');
                  this.data = response.data;
                } catch (error) {
                  // Handle error
                }
              }
            }
          };
          </script>

Explanation:

Plugin Definition: In `httpClient.js`, we define a plugin that sets up an Axios instance with a base URL and default headers. This instance is then added to the Vue app's global properties as `$http`.


Registering the Plugin: In `main.js`, we import and register the plugin using `app.use` and pass configuration options such as the base URL and headers.


Using the Plugin: In `ApiComponent.vue`, we use the global `$http` method provided by the plugin to make an HTTP GET request when a button is clicked. The response data is then displayed in the component.