DEV Community

Carlos Rodrigues
Carlos Rodrigues

Posted on • Updated on

Passing lots of props in Vue.js as a Pro 🧑🏼‍🚀

When developing a component in Vue, we often end up adding a lot of properties as the component grows and we usually tend to pass these properties individually.

To illustrate that, let's consider that we have the following object:

export default {
  setup() {
    const hero = ref({
      name: 'Batman',
      realName: 'Bruce Wayne',
      identity: 'Secret',
      citizenship: 'American'
    })

    return {
      hero
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

and then we pass the properties of the object individually to the Hero component:

<template>
  <Hero 
    :name="hero.name"
    :real-name="hero.realName"
    :identity="hero.identity"
    :citizenship="hero.citizenship"
  />
</template
Enter fullscreen mode Exit fullscreen mode

Using v-bind

There is nothing wrong with the approach above, but we can make our lives easier by just passing the whole object using v-bind, and automatically all its props will be bound into the component:

<template>
  <Hero v-bind="hero" />
</template
Enter fullscreen mode Exit fullscreen mode

Using v-on

We can do the same with events, passing them via v-on through an object handler:

const heroEventsHandler = {
  onChangeRealName: () => hero.value.realName = 'Robert',
  onChangeIdentity: () => hero.value.identity = 'Public'
}
Enter fullscreen mode Exit fullscreen mode

Note: Assuming that our Hero Component expose these events: @on-change-real-name and @on-change-identity

<template>
  <Hero v-on="heroEventsHandler" />
</template
Enter fullscreen mode Exit fullscreen mode

At the end of the day, instead of having something like this:

<template>
  <Hero 
    :name="hero.name"
    :real-name="hero.realName"
    :identity="hero.identity"
    :citizenship="hero.citizenship"
    @on-change-real-name="onChangeRealName"
    @on-change-identity="onChangeIdentity"
  />
</template
Enter fullscreen mode Exit fullscreen mode

We would have something like this:

<template>
  <Hero 
    v-bind="hero"
    v-on="heroEventsHandler"
  />
</template
Enter fullscreen mode Exit fullscreen mode

How cool is that, right? Much more straightforward!

I hope you found it helpful. Leave a comment if you have used those directives before, and stay tuned for more Vue tips.

Thanks for reading.

Top comments (0)