Skip to content

Instantly share code, notes, and snippets.

@rwaddin
Last active March 18, 2021 07:31
Show Gist options
  • Save rwaddin/17cdd5085e8ab03e70c55f0013fb7c90 to your computer and use it in GitHub Desktop.
Save rwaddin/17cdd5085e8ab03e70c55f0013fb7c90 to your computer and use it in GitHub Desktop.
Parsing data child to parent vuejs with emit
<template>
<div class="child">
<!-- Simplest - call `$emit()` inline-->
<button type="button" name="button" v-on:click="$emit('increment')">Click me to increment!</button>
<!-- set a variable then trigger a method which calls `$emit()` -->
<label for="child-input">Child input: </label>
<input id="child-input" type="text" name="msg" v-model="childMessage" v-on:keyup="emitToParent">
</div>
</template>
<script>
export default {
data() {
return {
childMessage: ''
}
},
name: 'Child',
methods: {
// Define the method that emits data to the parent as the first parameter to `$emit()`.
// This is referenced in the <template> call in the parent. The second parameter is the payload.
emitToParent (event) {
this.$emit('childToParent', this.childMessage)
}
}
}
</script>
<!-- Parent.vue -->
<template>
<div>
<!--
Listen for `childToParent`: the first parameter of the `$emit` method
in the child component. We're also listening and reacting to an
`increment` event - in this case, we increment a counter inline.
-->
<Child :parentData="myData" v-on:childToParent="onChildClick" v-on:increment="counter++"></PassProps>
</div>
</template>
<script>
import Child from '@/components/Child.vue'
export default {
data () {
return {
counter: 0,
fromChild: '', // This value is set to the value emitted by the child
}
},
name: 'about',
components: {
Child
},
methods: {
// Triggered when `childToParent` event is emitted by the child.
onChildClick (value) {
this.fromChild = value
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment