Vue pass data from child to parent component

Pass with emit event

ParentComponent.vue

When updateName get emit from child component update nameParent to new value in that case the nameParent will be "New name"

<template>
  <div>
    <h3>Parent Component</h3>
    {{ nameParent }}
    <ChildComponent :name="nameParent" @updateName="(val) => nameParent = val" />
  </div>
</template>
    
<script>
export default {
  data() {
    return {
      nameParent: 'Tada'
    }
  },
  components: {
    ChildComponent: () => import('./ChildComponent')
  }
}
</script>

ChildComponent.vue

This code will fire event updateName to parent component when user click on "Update Name" button with the new name value of "New name"

<template>
  <div>
    <h4>Child Component</h4>
    <p style="color: red">{{ name }}</p>
    <button @click="updateParentData">Update Name</button>
  </div>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      required: true
    }
  },
  methods: {
    updateParentData() {
      return this.$emit('updateName', 'New name');
    }
  }
}
</script>

Two way binding, emit value to prop directly

ParentComponent.vue

When passing the prop with sync it will listen to emit with update and change the "nameParent" according in this case

<template>
  <div>
    <h3>Parent Component</h3>
    {{ nameParent }}
    <ChildComponent :name.sync="nameParent" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      nameParent: 'Tada'
    }
  },
  components: {
    ChildComponent: () => import('./ChildComponent')
  }
}
</script>

ChildComponent.vue

The "updateParentData" in this case will not emit event but rather emit value to props so when clicking the "Update Name" button the nameParent will update to "New name"

<template>
  <div>
    <h4>Child Component</h4>
    <p style="color: red">{{ name }}</p>
    <button @click="updateParentData">Update Name</button>
  </div>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      required: true
    }
  },
  methods: {
    updateParentData() {
      return this.$emit('update:name', 'New name');
    }
  }
}
</script>