Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call methods in App.vue from the vue components

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?

like image 562
Arun D Avatar asked Apr 08 '17 10:04

Arun D


People also ask

How do you call a method from another component Vue?

Just add a $on function to the $root instance and call form any other component accessing the $root and calling $emit function.

How do you call one component from another component in VueJS?

Using $refs Using the $refs property is a great and simple way of calling a components method from the parent component so to reference the before mentioned scenarios this would be the parent-to-child scenario.

How do you write methods in Vue components?

Methods are defined either inside the method property or in Single File components. Here's how: inside the method property: **new Vue({ methods: { ** // add your function associated to event. in Single File Components: < script > export default { methods: { // add the function associated to event.


1 Answers

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");
        }
    }
})
like image 100
Egor Stambakio Avatar answered Nov 12 '22 16:11

Egor Stambakio