How to add custom properties to Vue modules and instances

Viewed 2719

When you inspect a Vue component that you have imported, you will get something like this:

import ClickB from 'ClickB.vue';
console.log(ClickB);

enter image description here

I have seen that nuxt adds a custom property there (called _nuxt), just like there is _ssrRegister. I have 2 questions:

  1. How is it possible to add properties to the component?
  2. Can you pass that property from the component to its instances?
2 Answers

It is simple. Just decorate Vue prototype like this to add instance method:

import Vue from 'vue';

// Adding an instance method
Vue.prototype.$someMethod = function (methodOptions) {
    // Your own logic...
}

As a good practice, this code should be in your index.js or main.js file. Taking it one step further, you should put this code inside plugins as explained in Vue documentation for plugins.

Related