DEV Community

Scott
Scott

Posted on

How to "destructure" props in Vue like you did in React

Coming from React, I really enjoyed passing down destructured props to child components, I thought it made the components cleaner and easier to read. Recently, I've been working a lot in Vue and thought Id share how to do the same thing we can do in React but in Vue.

The Skinny

<my-component v-bind="propsObjectIWantToSendToChild" />
Enter fullscreen mode Exit fullscreen mode

The not so skinny

What does v-bind do?

From the docs:

Dynamically bind one or more attributes, or a component prop to an expression.

What does this mean?

We know in HTML we can add a class as an attribute

<p class="my-class">Here is a p tag</p>
Enter fullscreen mode Exit fullscreen mode

But in Vue we might want to conditionally set the class using some Javascript.

computed: {
  loadingClass() {
    return isLoading ? 'active' : '';
  }
}

// template
<p v-bind:class="loadingClass">Here is a p tag</p>
Enter fullscreen mode Exit fullscreen mode

Or we can use the nice shorthand Vue gives us for v-bind, removing v-bind and just adding :class

<p :class="loadingClass">Here is a p tag</p>
Enter fullscreen mode Exit fullscreen mode

Passing props

Usually, if I want to pass props to a component, we do something similar to the example above.

<my-component :user-id="userId" :user-name="userName" />
Enter fullscreen mode Exit fullscreen mode

But sometimes we need to pass more than 1 or 2 props and it becomes a bit hard to keep track of and bloats the template.

Insert v-bind

We can take the same component and do something like the following.

// my_parent_component.vue
computed: {
  myProps() { //please dont use this as a computed function name :)
   return { userName: this.userName, userId: this.userId };
  },
},
// template
<my-component v-bind="myProps" />
Enter fullscreen mode Exit fullscreen mode

Then in my component you declare your props like any other component:

// my_component.vue
props: {
  userId: {
    required: true,
    type: String,
  },
  userName: {
    required: true,
    type: String,
  },
},
Enter fullscreen mode Exit fullscreen mode

Hopefully this helps clean your templates up and you learned something. If you liked the content or have any questions please comment/like below and visit me at https://scottistern.com

Resources

Top comments (0)