Mike3355
Mike3355

Reputation: 12081

Emitting data from parent to child in vue not working

There are many questions with this same issue, but I cannot seem to figure it out. I am trying to send an event from my parent to my child. I know how the workflow is supposed to look like.

Read only life cycle: Parent > Prop > Child

Read/Update life cycle: Parent > Prop > Child > Emit > Parent > Update > Child Updates

I am using a prop, but there is nothing happening.

In the parent component:

         <v-row :class="'mb-3'" no-gutters >
            <v-col v-for="n in urlCount" :key='n'>
                <v-card class="pa-2" outlined tile >
                    <team-url :editField="update"></team-url>
                </v-card>
            </v-col>
        </v-row>

update(): string {
    return 'enableEdit';
}

In the child component:

editField = '';

showField(url: string): string {
    return (this.url[url] == '' || this.editField == url)
}

I am trying to set the editField variable to enableEdit or send an event to trigger a method but I have not been able to successfully do it.

Upvotes: 0

Views: 646

Answers (1)

tony19
tony19

Reputation: 138286

A parent wouldn't be sending events down to a child. Instead, the parent binds data to a child prop, and the child emits events (including any data) up to its parent. Props down, events up.

In your code, it looks like the parent component is binding the update computed prop to the editField prop of the team-url child component. The expected behavior in your question is a bit unclear, but I'll explain possible scenarios.

If you want team-url to react to changes in editField from the parent (e.g., to run a method), use a watcher:

// TeamUrl.vue
export default {
  props: ['editField'],
  watch: {
    editField(newValue) {
      this.onEditFieldChange(newValue)
    }
  },
  methods: {
    onEditFieldChange(newValue) {
      console.log(newValue)
    }
  },
}

If you want team-url to communicate data with its parent, the parent would first setup an event listener with v-on:EVENT_NAME="METHOD_NAME" (or @EVENT_NAME="METHOD_NAME" shorthand):

// Parent.vue
<template>
  <team-url @my-event="onMyEvent" />
</template>

<script>
export default {
  methods: {
    onMyEvent(data) {
      console.log(data)
    }
  } 
}
</script>

And team-url could then send an event to its parent with vm.$emit:

// TeamUrl.vue
export default {
  methods: {
    emitEventToParent(myData) {
      this.$emit('my-event', myData)
    }
  }
}

Upvotes: 2

Related Questions