Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a parent method from child component in Vue.js?

I am trying to call a parent/root level method on a child component in Vue.js, but I keep getting a message saying TypeError: this.addStatusClass is not a function.

Vue.component('spmodal', {
    props: ['addStatusClass'],
    created: function() {
        this.getEnvironments();
    },
    methods: {
        getEnvironments: function() {
            this.addStatusClass('test');
        }
    }
});

new Vue({
    el: '#app',
    methods: {
        addStatusClass(data) {
          console.log(data);
        }
    }
});

Here is a full JSBIN example: http://jsbin.com/tomorozonu/edit?js,console,output

If I call this.$parent.addStatusClass('test'); it works fine, but based on the Vue.js documentation, this is bad practice and I should be using props which is not working.

like image 397
ATLChris Avatar asked Apr 30 '16 12:04

ATLChris


People also ask

How do you call parent component method from child Vue?

To call parent method with component with Vue. js, we can get the parent component's method from the $parent property. to define the child component with Vue. component .

How do you access the child component property in the parent component Vue?

To access child component's data from parent with Vue. js, we can assign a ref to the child component. And then we can access the child component data as a property of the ref. to assign the markdown ref to the markdown component.

How do you pass data from parent component to child component in Vue?

The way it works is that you define your data on the parent component and give it a value, then you go to the child component that needs that data and pass the value to a prop attribute so the data becomes a property in the child component. You can use the root component (App.


1 Answers

specifying the prop does nothing on its own, you have to actually pass something to it from the parent - in this case, the function.

<spmodal :add-status-class="addStatusClass"></spmodal>
like image 146
Linus Borg Avatar answered Oct 22 '22 00:10

Linus Borg