Search code examples
javascriptvue.jsvuejs2bootstrap-vue

Listen to event in VueJS parent component to call a method


My VueJS 2 application contains a parent component and a child component. The parent passes a prop called items to the child.

When the user clicks on a button in the child component it emits a refresh event like this:

$emit('refresh', category.id)

I'd like to listen to this event in the parent component and, if the event is received, trigger a method, e.g. alert().

As far as I have understood the `` the v-on listener can be attached to e.g. a button or else. The problem is that my parent component does not have something like a button for this.

To make things clearer here's what I'm thinking of:

  1. Parent component is loaded. It calls a getData() function which result is passed as a prop to the child component.
  2. The user clicks a button in the child component.
  3. The child component triggers an event.
  4. The parent component again calls getData() and updated the prop passed to the child.

Solution

  • By assuming that you have in child component a code like :

      <button v-on:click="$emit('refresh', category.id)" ...
    

    in the parent one you should have this

                         <child v-on:refresh="refreshParent"   />
     event emitted from child  ---------^       ^-------- its handler method in the parent 
    

    in the parent methods :

      methods:{
        refreshParent(idCateg){
            this.getData()
         }
      ....
      }