Conor
Conor

Reputation: 2563

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.

Upvotes: 1

Views: 4802

Answers (3)

Jns
Jns

Reputation: 3257

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

Upvotes: 3

Kapitan Teemo
Kapitan Teemo

Reputation: 2164

you can use vue event bus to trigger events from different components.

First, initialize Vue.prototype.$bus = new Vue(); in your main.js file.

let your parent component send events:

validate(event) {
    if (event.target.value == 'hello') {
        this.$bus.$emit('throw', 'Hi')
    }
}

then let your child component listen:

created() {
    this.$bus.$on('throw', ($event) => {
        console.log($event)  //shows 'Hi'
    })
}

Upvotes: 5

waleed ali
waleed ali

Reputation: 1195

Short Answer: You can use props and watch/computed properties for that purpose.

Parent Component:

As per your case, you can define foo as your data property in parent-component and bind foo to input element using v-model (the recommended way) OR keep it the same as you have already done (listening to the input event) and once, it is equal to some value hello (in your case) it changes the foo to true.

As soon as foo value changes, Vue reactivity comes into play and, it informs/re-renders the child component.

Child Component:

Now, here, you can watch for changes in the prop and once it turns true you can call a function/method (someFunction).

Here is the fiddle for your understanding

Upvotes: 1

Related Questions