Disclaimer: We assume here that you know the basics of vuejs

So lets begin:

Create a new empty js file and link the file in index.template.html(you will find it in your vue project). Lets name the empty js file as ext.js, this is your external javascript file

Now add the following code in the file

function callingVuejsFunction(data) {

var event = new CustomEvent("hakunaMatata",{

detail: {

message: "naiveTechNoobs",

info: data

}});

In the above code we create a function called callingVuejsFunction inside which we create a new custom event called hakunaMatata (the event name can be anything you want). The event has a field called detail, inside which you can add a json of whatever data you want. For the example sake wehave added a message and info object. Now it’s time to listen to the event that you just created.

Add the below code in the mounted() hook of the vuejs component you want to use it in

window.addEventListener('hakunaMatata', this.displayData)

Here we create an event listener that listens to the event hakunaMatata we created in ext.js file. The event listener has an additional parameter in which you specify the function you want to trigger (in this example its this.displayData).

Now create the triggered function inside your methods() hook and do whatever you want with the received data. In this example we create displayData() function in methods() hook to do something like this

displayData: function(e) {

console.log(e.detail.message+" "+e.detail.info)

},

That’s about it. Now whenever you call callingVuejsFunction(data) it will trigger hakunaMatata event which will be listened by the event listener and will in turn trigger displayData() function.

QOL tip:

Sometimes you would also want to destroy the event listener when its work is done. All you have to do is:

window.removeEventListener('hakunaMatata',this.displayData, false);

We would advice you to add the above code in the destroyed() hook of your component.