Uncoke
Uncoke

Reputation: 1902

Vue.JS import custom module

I have created a module greatings.js like this one:

function greatings() {
  this.hello = function() {
    return 'hello!';
  }

  this.goodbye = function() {
    return 'goodbye!';
  }
}

module.exports = greatings;

Then I imported it into main.js in VUE.JS just like:

import greatings from './assets/js/greatings';
Vue.use(greatings);

Now I would like to use it in my components but if I do it I got an error:

  mounted() {
    this.greatings.hello();
  }

ERROR: Error in mounted hook: "TypeError: Cannot read property 'hello' of undefined"

How to fix it and be able to use my greatings? Thanks for any help!

Upvotes: 1

Views: 3363

Answers (2)

Igor Moraru
Igor Moraru

Reputation: 7729

When using Vue.use() to register a custom plugin, it has to define an install() function, which is called by Vue. From docs:

A Vue.js plugin should expose an install method. The method will be called with the Vue constructor as the first argument, along with possible options.

See the provided example, for all the options you have when creating a custom plugin: https://v2.vuejs.org/v2/guide/plugins.html

Upvotes: 1

Basir Askari
Basir Askari

Reputation: 61

greatings.js file should be like this

export default {
  hello() {
    return "hello";
  },
  goodbye() {
    return "goodbye!";
  }
};

and import in any file you want to use like this

import greatings from './assets/js/greatings';

and call any function do you want. remove this function Vue.use(greatings);

Upvotes: 2

Related Questions