0

I have parent and chidl component... I need to run child method, when i click on button in parent. Example code:

Parent

<template>
 <child-component></child-component>
 <button>Open Modal in child Component (set modal = true in child component)</button>
</template>

Child:

<template>
<div v-if="modal">
 <button @click="modal = false">Close</button>
</div>
</template>
<script>
export default {
  data() {
    return {
     modal: false
    }
  } 
}
</script>
  • Here you can find a similar problem with a solution: https://stackoverflow.com/a/45463576/4267716 – amaj Feb 20 '20 at 15:09

2 Answers2

0

In vue you can pass a function as a prop. So you could add a function to alternate model within your parent component then pass it into your child so it can be used normally. I'll put a simple example below.

small edit, you can bind a class like a hidden/reveal class using the status which is bound to the modal state

// Html
<div id="app">
     <child v-bind:on-click="toggleModal" v-bind:status="modal" />
</div>


// Parent Component
var sample = new Vue({
     el: '#app',
     data: {
        modal: false
     },
     methods: {
        toggleModal() {
           this.modal = !this.modal
        }
     }
});

// Child component with function prop
Vue.component('child', {
     props: {
        onClick: Function,
        status: Boolean
     }
     template: '<button v-on:click="onClick()">Press Me</div>'
});
emoore
  • 314
  • 2
  • 11
0

You can achieve this via different implementations. The most common one is via emit (another alternative is via dispatching actions if you are using the Redux pattern)

First, you want to catch the even on the parent component and emit an event. So this should be your template.

<template>
 <child-component></child-component>
 <button @click="click">Open Modal in child Component (set modal = true in child component)</button>
</template>

Then you have to emit an event (from the parent component) on the function called when a click was made. Something like:

click: function() {
  this.$emit('update');
}

Lastly, your child component needs to "hear" that event. You can achieve that with something like that on the created function of the child component:

this.$parent.$on('update', this.updateModal);

this.updateModal is a function on your child component which just flips the value of the boolean.

Alexis Pavlidis
  • 1,080
  • 1
  • 11
  • 21