This article was published over a year ago, so please be aware that some content may be out of date.

Tuesday, August 21, 2018 3:48 PM

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.

Vue
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.
I hope you learned something useful.
If you've made it this far, you might like to follow me on Twitter where I post similar content and connect with like-minded people.
Follow me on Twitter
Analytics
Add Google Analytics To A Nuxt Js App
Add Google Analytics To A Nuxt Js App

Let me show you how to add Google Analytics to your Nuxt JS app, whilst ensuring that you comply with GDPR legislation with a cookie banner.

Read this article
JavaScript
Add Comments To Your Blog In Under Five Minutes
Add Comments To Your Blog In Under Five Minutes

Utterances is a free and open source comment system that uses GitHub issues to track comments on a web page. In this article I'll show you how to get Utterances up and running and share some tips on how to configure it for Nuxt JS.

Read this article
Privacy Policy
Copyright © 2021 Carl Cassar. All Rights Reserved.