5 years ago Tue, Aug 21, 2018

Prop Destructuring In Vue Js

In a couple of recent tweets, Caleb Porzio demonstrated an easy way to pass Javascript object properties to a child component without declaring a separate prop for each property.

Here's how it works. Let's say that we have a Javascript object with several properties in the data object of a Vue JS component:

data() {
    return {
        post: {
            id: 1,
            name: 'Prop destructuring in Vue Js',
            author: 'Carl Cassar'
        }
    };
}

Imagine that you want to pass this data to a child component. One way of doing it, is to declare a prop for each of the object's properties and pass each one through individually.

<post :id="post.id" :name="post.name" :author="post.author"> </post>

Whilst there is nothing wrong with this approach, it is also possible to pass through the whole object at once by using the v-bind directive.

<post v-bind="post"></post>

Behind the scenes, Vue will 'destructure' the post object and pass through each property to the 'post` component as a prop.

props: {
    id: Number,
    name: String,
    author: Object
}

As you can see, this still allows us to validate the prop and set a sensible default as we would normally.

In the interest of giving credit where credit is due, here's the original tweet with Caleb's great tip:


You can see all of the uses for the v-bind directive in the docs and follow @calebporzio on Twitter. He's been posting some great tips recently and is well worth following.

Thank you for reading this article.

If you've made it this far, you might like to connect with me on 𝕏 where I post similar content and interact with like-minded people. If this article was helpful to you I'd really appreciate it if you would consider buying me a coffee.