1

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!

1

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. How to call the hello function from mounted(){} ? greatings.hello() ? I got error...
you can call hello like this greatings.hello();
mounted(){ greatings.hello(); }
_assets_js_greatings__WEBPACK_IMPORTED_MODULE_10___default.a.hello is not a function"
Maybe it's a webpack error... I copied the same code ad above in my component. It loads greatings.js but I got the error in mount()
1

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

1 Comment

Thanks Igor, this is very helpful, but I'm trying to reuse my old script; a plugin requires too many changes. I'll evaluate if I really need a plugin. Thanks for suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.