Vue prototype helpers for common code

Vue prototype helpers for common code

Tired of importing your API module or other utility functions all over your app and want to stop repeating yourself? Use Vue prototypes!

ยท

2 min read

When developing a Vue application some modules or functions are often needed in many if not all your components. It might be an HTTP request library like Axios or some utility function that you use a lot throughout your app. If you want to stop repeating yourself you can use Vue prototypes to make it accessible in every single file component without importing it explicitly. This way you can also do common repeating code in the prototype module.

A simple example

Your typical Vue app will have a file src/main.js where your Vue application is mounted. It might be a good rule to define all your prototypes in one place so it's easy to find them for other developers (and yourself in some months from now).

import Vue from 'vue'
import App from './App.vue'

//Prototype definitions
Vue.prototype.$print = (text) => {
  console.log(text);
};

new Vue({
  render: h => h(App)
}).$mount('#app')

Now the function print is accessible from this.$print in all Vue components.

<template>
    <div>App component</div>
</template>

<script>
export default {
  mounted() {
    this.$print('App component mounted');
  },
}
</script>

When the App component mounts it will print App component mounted using the prototype function. Let's look at a more useful example.

Example using an API module

Many applications need to send HTTP requests to a REST API. We can utilize prototypes to avoid repeating code for setting up base urls, reading data and handling errors.

import Vue from 'vue'
import App from './App.vue'
import api from './api'

//Prototype definitions
Vue.prototype.$api = api;

new Vue({
  render: h => h(App)
}).$mount('#app')

So, what is this api module doing? It's a custom js module in src/api/index.js that helps to send HTTP requests to your API. I am using this example because this is something I often find myself needing in web applications. Remember to npm install axios if copying this example. Here's the api module.

import axios from 'axios';

const instance = axios.create({
    baseURL: 'https://some-domain.com/api/',
    timeout: 15000,
    headers: {'X-Custom-Header': 'foobar'}
});

export default instance;

Now we can use the API directly in all components.

<template>
  <div>Some component</div>
</template>

<script>

export default {
  async mounted() {
    try {
      const response = await this.$api.get('some-api-endpoint');
      console.log(response.data);
    } catch(e) {
      // Handle error here
    }
  },
}

</script>

Summary

Using Vue prototypes can help to avoid repeating code and importing the same module all over the application. The examples in this article are simple but there are really no limits to what you can use prototypes for. If you have an example of how you use Vue prototypes please comment below!

ย