This article was published over a year ago, so please be aware that some content may be out of date.
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.
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:
📒📚 In @vuejs, instead of passing a bunch of object properties into a component as props, you can use v-bind as kind of a "prop destructuring" pic.twitter.com/swZrNrmMou
— Caleb Porzio (@calebporzio) August 29, 2018
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.
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.
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.