Simple call to vue function in Methods from external Javascript file

So i’m pretty new at Vuejs, I looked throughout the forum and on stackOverflow and found some solutions but none of them seem to have worked or i was doing it wrong. I have an example below of what I wanted to achieve. I’m currently using vue.cli for my project. What i would like to happen is very simple. On mounting of the app, the pleasework function is called. I have this part working. but it never fires the internal function tester() which i would like to happen. Am i headed in the right direction or should I be going another direction?

Thank you.

main.js

new Vue({ el: '#app',
                render: h => h(App)
             })

App.vue

import local_file from './scripts/testJS'

Methods: {

    tester: function (){
      alert("great - function was called from external JS!")
    }

}

mounted: function(){

    local_file.pleasework();

}

testJS.js

export default{
    pleasework: function(){
        tester();
        console.log("pleasework fired")
    }
}

The tester() method does not exist in the global scope, and your pleasework() function has no reference to the app instance.

You either have to import your app instance into testJS.js:

// App.vue
import local_file from './scripts/testJS'

export default new Vue(...)

// testJS.js
import App from '../App'

export default{
    pleasework: function(){
        App.tester();
        console.log("pleasework fired")
    }
}

Alternatively you can pass the app instance as a parameter to pleasework():

//  App.js
mounted: function() {
    local_file.pleasework(this); // give pleasework a reference to the Vue instance 
}

// testJS.js
export default{
    pleasework: function(app){
        app.tester();
        console.log("pleasework fired")
    }
}

Or, and not recommended but incredibly useful (particularly for doing stuff to the app direct from the console) you could put the app on the global scope:

// App.vue
import local_file from './scripts/testJS'

window.App =  new Vue(...)

// testJS.js
export default{
    pleasework: function(){
        window.App.tester();  // window. not necessary, but help indicate this is global
        console.log("pleasework fired")
    }
}
1 Like

Thank you very much!