简体   繁体   中英

Vue-js communication between child components

I have a parent component that steps thru a list and creates a <ticket-item> child component for each item. The <ticket-item> component displays a link that pops a modal and passes in that list item's ticket object. I also want to pop the modal if the user clicks on the <appointment-button> child component in another list on the page. I emit an event in <appointment-button> to the root instance and listen for that root event in the <ticket-item> component. Below are snippets of code from each component:

<ticket-list> component which lists each <ticket-item> component:

<tr v-for="ticket in tickets" :key="ticket.id">
    <td><ticket-item :ticket="ticket"></ticket-item></td>
    <td>{{ticket.amount}}</td>
</tr>

<ticket-item> component mounted event:

self = this
this.$root.$on('openTicket-'+this.ticket.id, data => {
  console.log('data='+data+', ticket.id='+self.ticket.id)
  //event name has ticket id in it, but checking here anyway
  if (self.ticket.id==data) {
    self.editTicket = true
  }
})

<appointment-button> component that emits event:

openTicket() {
  this.$root.$emit('openTicket-'+this.appt.ticket.id, this.appt.ticket.id)
}

When I click on the appointment button and emit the event above, I get this console output from my <ticket-item> components that are loaded:

控制台输出 1

So only one line of output was printed, but I have 8 <ticket-item> components in my test. If I remove '-'+ticket.id from the event name, then I get this console output:

控制台输出 2

So 8 lines that match the number of <ticket-item> components, but all use the data from the last component's ticket prop. Any idea what I'm missing here? Why would the mounted lifecycle event not have the correct 'ticket' prop that's passed in from the parent (list)? I know from the rest of the code I've written that any props passed into a component from a parent are available in the mounted event.

Update:

If I create an appointment and check the user in, a new ticket item is created. Now the root listener is updated to use this latest id. I can open the ticket from the appointment button (listener), but none of the others work obviously...

Yes. you're correct. I don't need self=this. I put const in front and that fixed it too, but no need anyway.

Thanks!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM