Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 22, 2022 03:18 pm GMT

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    }  }}

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

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

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'}

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

<template>  <Hero v-on="heroEventsHandler" /></template

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

We would have something like this:

<template>  <Hero     v-bind="hero"    v-on="heroEventsHandler"  /></template

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.


Original Link: https://dev.to/kaduln2/passing-lots-of-props-in-vuejs-as-a-pro-418k

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To