LC Yoong LC Yoong - 22 days ago 8
Javascript Question

How to call functions declared out of a Vuejs instance?

This is a pseudocode to illustrate my question. When the script is run, it will encounter the error func1 is not defined. How can I go about this?

app.js

require ('./helper');
new Vue ({
el: "#app",

created: function () {
func1()
}
});


helper.js

module.exports = function () {
$.notify('Hi', {
position: "bottom right",
className: "success"
});
};


Thanks in advance!

Answer Source

You might have to save the imported function to a variable in your app.js file. It depends on what bundler you use (e.g. browserify or webpack or else). Functions declared outside of the parameter object you are passing to Vue should be accessible:

// app.js
var func1 = require('./helper');
new Vue ({
    el: "#app",

    created: function () {
        func1();
    }
});

In your helpers.js, you need a reference to jQuery. You can either include the library (jQuery and $ will be available globally on the window object) or like in the example below, install it from https://www.npmjs.com/package/jquery and bundle it with your own code.

// helper.js
var $ = require('jquery');

module.exports = function () {
    $.notify('Hi', {
        position: "bottom right",
        className: "success"
    });
};