By Child Component Refs
Assign a ref
id to child component, and you can access the child component using this.$refs.[id]
.
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 },})
Code of ChildForm.
<template>
...
</template>
<script>
export default {
name: 'NowForm',
props: ['item'],
methods: {
submit() {
...
}
}
}
</script>
By Event Bus
If you dislike the tight coupling using ref
, you can use Event Bus instead.
import ChildForm from './components/ChildForm'new Vue({ el: '#app', data: { item: {}, bus: new Vue(), }, template: ` <div> <ChildForm :item="item" :bus="bus" ref="form" /> <button type="submit" @click.prevent="submit">Post</button> </div> `, methods: { submit() { this.bus.$emit('submit') } }, components: { ChildForm },})
Code of ChildForm.
<template>
...
</template>
<script>
export default {
name: 'NowForm',
props: ['item', 'bus'],
methods: {
submit() {
...
}
},
mounted() {
this.bus.$on('submit', this.submit)
},
}
</script>