16

I have a vue component and a vue element declaration as given below

Vue.component('todo-item', {
    template: '<li>This is a todo</li>'
    methods: {
        test: function() {
            
            // I am getting an error here
            app.aNewFunction();
        }
    }
})

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!'
    },
    methods: {
        aNewFunction: function() {
            alert("inside");
        }
    }
}) 

How to call a method in vue app from the vue component?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Arun D
  • 2,369
  • 5
  • 27
  • 39

2 Answers2

22

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");
        }
    }
})
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35
13

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...';
        },
    }
});
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Yaser Khahani
  • 685
  • 7
  • 15
  • 2
    This is the correct way to do it if you want to keep your components decoupled from the app. In a few words, if you want to have re-usable components you want to follow @YaserKH example. I would recommend this as the correct answer based on architectural best practices. – suchislife Sep 18 '19 at 18:10
  • 1
    A little late to the party, but this is the way to go. You could also use routes for more complexe application I guess. – Erick Audet Mar 06 '21 at 12:35