0

I have to call a Vue.js function from an external JavaScript file, but it's not working. Below I have given the code that I have tried.

// external js file 
import vm from './vue.js';

function callingVuejsFunction(data) {  
    this.vm.displayData()
}

// Vuejs file
var vm = new Vue({
    el: '#app',
    data: {
        firstname : '' ,
        lastname  :  ''
    },
    methods:{
        displayData: function( ) {
            alert()
        } 
    } 
})
3
  • 1
    try vm.displayData() instead this.vm.displayData() Commented Feb 2, 2021 at 11:21
  • its not calling. Commented Feb 2, 2021 at 12:00
  • You need the reference to your Vue application - not to the Vue framework itself. Change the main.js in your Vue application so that it assigned the root Vue instance to a global variable (e.g. window.myApp) and then refer to this variable in your external script. Commented Feb 2, 2021 at 13:56

2 Answers 2

2

You can use vm.$options.methods.displayData():

var vm = new Vue({
  el: '#app',
  data: {
    firstname: '',
    lastname: ''
  },
  methods: {
    displayData: function(msg) {
      alert(msg)
    }
  }
})

vm.$options.methods.displayData('I was called externally!')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app"></div>

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

1 Comment

Props for an example that runs in the stackoverflow window 👍🏼
0

export default { 
    methods:{
      my_function(){
        alert('vue function trigger!!!')
      }
    },
    created () { 
        let _this = this 
        window.addEventListener('ready', function() { 
          _this.my_function()
        })
       
    }
}

Here is the perfect example of calling a vue method from javascript.

Comments

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.