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()
}
}
})
2 Answers 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>
answered Feb 2, 2021 at 14:26
Dan Knights
8,4184 gold badges28 silver badges55 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Phil H.
Props for an example that runs in the stackoverflow window 👍🏼
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.
answered Nov 30, 2022 at 14:47
user16249416
Comments
lang-js
vm.displayData()insteadthis.vm.displayData()main.jsin 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.