Search code examples
javascriptvue.jscomponentsinteraction

Parent to Child interaction in Vue


I would like to know how to make a parent-child interaction in Vue.

Let me give you a small example to explain it.

parent.vue file

<template>
    <div>
        <input @input="validate" type="text" />
        <child-component></child-component>
    </div>
</template>

<script>
    export default {
        methods: {
            validate(event) {
                if (event.target.value == 'hello') {
                    // make my child component to do something
                }
            }
        }
    }
</script>

child.vue file

<script>
    export default {
        methods: {
            someFunction() {
                alert('Success');
            }
        }
    }
</script>

Note: This is just an example. My actual situation is little complicated to explain here

In this example, I would like to know how to trigger the function someFunction() in the child component when the if condition in the parent component becomes true.


Solution

  • You could assign a ref to your child component and then use $refs to call the method on the child component directly.

    <template>
        <div>
            <input @input="validate" type="text" />
            <child-component ref="child"></child-component>
        </div>
    </template>
    
    <script>
        export default {
            methods: {
                validate(event) {
                    if (event.target.value == 'hello') {
                        this.$refs.child.someFunction();
                    }
                }
            }
        }
    </script>
    

    Vue Docs Ref