Vue.js Parent Call Child Component Method

Nov 30, 2017

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>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.