vuejs event from child to parent code example
Example 1: vue pass data from child to parent
<script>
import Child from '@/components/Child.vue'
export default {
components: {
Child
}
}
</script>
/****************************************************************/
<template>
<div>
<Child title="This is my title"></Child>
<Child :parentData="{msg: 'xxx'}"></Child>
<Child :parentData="myData"></Child>
<Child :stringProp="stringMessage"></Child>
</div>
</template>
/****************************************************************/
<script>
export default {
name: 'Child',
props: {
parentData: Object,
stringProp: String,
title: String
}
}
</script>
/****************************************************************/
<template>
<div>
<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: '',
}
},
name: 'about',
components: {
Child
},
methods: {
onChildClick (value) {
this.fromChild = value
}
}
}
</script>
/****************************************************************/
<template>
<div class="child">
<button type="button" name="button" v-on:click="$emit('increment')">Click me to increment!</button>
<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: {
emitToParent (event) {
this.$emit('childToParent', this.childMessage)
}
}
}
</script>
Example 2: trigger a function inside child from parent vue
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {}
},
template: `
<div>
<ChildForm :item="item" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.$refs.form.submit()
}
},
components: { ChildForm },
})