[Vuejs]-How to pass a function down to child component in Vue?

0👍

UPDATED: at grandparent I forgot to pass prop to child

<LazyDataLeagueGeneral
                  @changeLoadingBar="changeLoadingBar"    
                  :changeLoadingBar="changeLoadingBar"             
                />

call changeLoadingBar directly from a grandChild: this.changeLoadingBar(false);

another way is to just use Provide/inject (will make indirect call to changeLoadingbar function)

Grandparent component:

provide() {
    return {
      callChangeLoadingBar: this.changeLoadingBar,
    };
  },

on grandchild component TeamStanding:

inject:[
    'callChangeLoadingBar'
  ],

and just call indirectly changeLoadingBar: this.callChangeLoadingBar(false)

0👍

Try this.

props: {
    changeLoadingBar: {
      type: Function,
      required: true, //true or false
      default: () => { this.myMethod() },
    },
  },
  methods: {
    myMethod() {
      alert("I'm Ok!");
    }
  }

0👍

Passing down function props like this can quickly become very messy, especially with multiple n level child/grandchild/… components. In your example the Child component basically just proxies the function to the grandchild, all that is just redundant code.

This use case is typically ideal for a store (Vuex) or something like the eventHub pattern. Since you discarded Vuex as being overkill, then I would highly recommend to look into the eventHub pattern. In Vue 2 you can implement this pattern directly, or from Vue 3 it is recommended to use a 3rd party library like mitt. These libraries are tiny e.g. mitt is literally 200 bytes gzipped.

With this pattern your example case is trivial to implement and arguably much cleaner.

Leave a comment