Passing methods as props in Vue.js

Recently, I learned a new trick for keeping my Vue components more DRY.

You might be used to passing methods down to child components using custom event names like this…

// Calling custom fish component
<fish v-bind="{color, size}" @swim="swim" />
// Inside custom fish component
...
<button @click="$emit('swim', data)">
...

But there is another more succinct way…

// Calling custom fish component
<fish v-bind="{color, size, swim}" />
// Inside custom fish component
...
<button @click="swim(data)">
...

In the first case, Vue is using the event system, and in the second the method prop is a simple callback. There are some reasons for using one approach over another, depending on context, of course.

Some find that keeping data and callbacks separated into props and events makes their components more clear and easier to understand. The docs provide an important distinction about using a custom event…

…the child component is still completely decoupled from what happens outside of it. All it does is report information about its own activity, just in case a parent component might care.

So if you don’t need to completely decouple your child component from its parent, you too can benefit from this sleeker syntax!

If you liked this trick, you can check out Keeping props DRY in Vue.js.