1

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.
tony19
  • 125,647
  • 18
  • 229
  • 307
Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

2 Answers2

2

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()
     }
  ....
  }
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • Ah, I can see my problem now. Your code works fine. In my case I missed to see that the `$emit` is called from another component, i.e. my parent component didn't receive it because it actually is the "grandparent" component. – Robert Strauch Sep 04 '19 at 13:43
  • 1
    if you have a complicated situation where you have to share the same data between component i recommend to use Observable API like it explained [here](https://stackoverflow.com/questions/57710800/why-i-can-use-vuex/57712105#57712105) – Boussadjra Brahim Sep 04 '19 at 13:49
  • 1
    Had a well-hidden typo in my code. Your suggestion works fine :-) – Robert Strauch Sep 04 '19 at 14:10
2

you don't actually need a button for that purpose. I'll try to show you the code

ParentComponent.vue:

<child-comp @refresh="refreshFunc" />


methods: {
  refreshFunc (categoryId) {
    // here you go
  }
}

ChildComponent.vue:

  this.$emit('refresh', categoryId)
Asim Khan
  • 1,969
  • 12
  • 21