How to call a method in vue app from the vue component
You can execute root instance method like this: this.$root.methodName()
Vue.component('todo-item', {
template: '<li>This is a todo</li>',
methods: {
test: function() {
this.$root.aNewFunction();
}
},
mounted() {
this.test();
}
})
new Vue({
el: '#app',
template: '<todo-item></todo-item>',
methods: {
aNewFunction: function() {
alert("inside");
}
}
})
Another solution which I think it's more accorded with Vuejs architecture, it's to use events listener & emitter between child-component and its parent to make communications.
Check this simple fiddle as a vision
Vue.component('todo-item', {
template: '<li>This is a todo</li>',
methods: {
test: function() {
console.log('Emmit this Event.');
this.$emit('yourevent');
}
},
created() {
this.test();
}
});
new Vue({
el: '#vue-app',
data: {
'message': '',
},
methods: {
aNewFunction(event) {
console.log('yourevent Is Triggered!');
this.message = 'Do Stuff...';
},
}
});