Qar
Qar

Reputation: 1804

vue.js - right way to pass data from child to component?

I'm a bit confused regarding the right way to pass data from the root instance to a component.

Let's say I have this root instance:

const app = new Vue({
    el: '#app',

    data: {
        foo: 'bar'
    },
});

Then I have a component in a separate .vue file:

<template>
    <div>I'm a component!</div>
</template>

<script>
    export default {
        methods: {
            fooTest: function() {   
                console.log(this.$root.$data.foo);
            },
        },

        mounted() {
           this.fooTest();
        }
    }
</script>

This works fine. fooTest will get "bar" from the root instance data.

But is this the right way to do this? Or what is the best practice?

Upvotes: 1

Views: 6833

Answers (1)

Mani Jagadeesan
Mani Jagadeesan

Reputation: 24275

You should not use this.$root.$data. It may work for now, but your debugging effort will be significantly higher when your app grows. It will be a nightmare when you are working with a team of developers on the same app.

Instead you should use proper parent-child communication. Here are the official docs for that:

From parent to child: https://vuejs.org/guide/components.html#Passing-Data-with-Props

From child to parent: https://vuejs.org/guide/components.html#Using-v-on-with-Custom-Events

Here is another reference in StackOverflow to help you out: https://stackoverflow.com/a/40181591/654825

The jsFiddle example in that reference answer has a case of parent component passing data to child, and child component passing events to parent.

In short, parent can pass data to child and listen to child events as follows:

<child-component :data-from-parent="someValue" v-on:event-from-child="methodInParent"></child-component>

And child component can receive the above data from parent as follows:

Vue.component('child-component', {
    props: ["dataFromParent"],
    ...
});

You can follow that jsFiddle example for a better understanding of how this communication works.

Upvotes: 8

Related Questions