Static or Dynamic Props passing
Props have been passed a static value so far, as in
<blog-post title="My journey with Vue"></blog-post>
Props can also be assigned dynamically using v-bind or its shortcut:
<!-- Assigning a variable's value dynamically.-->
<blog-post :title="post.title"></blog-post>
<!-- Assigning the value of a complex expression dynamically -->
<blog-post :title="post.title + ' by ' + post.author.name"></blog-post>
We happen to pass string values in the two examples above, but any type of value can actually be passed to a prop.
Passing a Number
<!-- We need v-bind to tell vue that '42' is static -->
<!-- this is a JavaScript expression not a string -->
<blog-post :likes="42"></blog-post>
<!-- Assigning to the value of a variable dynamically -->
<blog-post :likes="post.likes"></blog-post>
Passing a Boolean
<!-- no value props will imply `true`. -->
<!-- If you don't set the is-published type to Boolean in props, it will be an empty string instead of "true" value. -->
<blog-post is-published></blog-post>
<!-- Even though `false` is static, we need v-bind to tell Vue that -->
<!-- this is a JavaScript expression not a string -->
<blog-post :is-published="false"></blog-post>
<!-- Dynamically assign to the value of a variable. -->
<blog-post :is-published="post.isPublished"></blog-post>
Passing an Array
<!--we need v-bind to tell Vue that -->
<!-- this is a JavaScript expression not a string even though array is static -->
<blog-post :comment-ids="[234, 266, 273]"></blog-post>
<!-- Dynamically assign to the value of a variable. -->
<blog-post :comment-ids="post.commentIds"></blog-post>
Passing an Object
<!-- we need v-bind to tell Vue that -->
<!-- this is a JavaScript expression rather than a string, even though the object is static, -->
<blog-post
:author="{
name: 'Veronica',
company: 'Veridian Dynamics'
}"
></blog-post>
<!-- assign the value of a variable dynamically -->
<blog-post :author="post.author"></blog-post>
Passing the Properties of an Object
You can use v-bind without an argument to pass all of an object's properties as props (v-bind instead of:prop-name).
Given a post object, for example:
post: {
id: 1,
title: 'My Journey with Vue'
}
The following template:
<blog-post v-bind="post"></blog-post>
Will be equivalent to:
<blog-post v-bind:id="post.id" v-bind:title="post.title"></blog-post>
One Way Data Flow
All props constitute a one-way-down binding between the child and parent properties. When the parent property updates, it will flow down to the child, but not vice versa. This prevents child components from changing the parent's state by inadvertently, making your app's data flow more difficult to understand.
Furthermore, if the parent component is updated, all props in the child component are updated with the most recent value. This means you shouldn't try to change a prop from within a child component. If you do, Vue will issue a console warning.
It's always enticing to modify a prop in one of two situation:
- The Vue.js prop is used to pass in an initial value, which the child component then wants to use as a local data property. It's better to create a local data property that utilizes the prop as its initial value in this case:
props: ['initialCounter'],
data() {
return {
counter: this.initialCounter
}
}
2. The prop is given as an unprocessed value that must be converted. It's better to define a calculated property using the prop's value in this case:
props: ['size'],
computed: {
normalizedSize() {
return this.size.trim().toLowerCase()
}
}
Note: Note that with JavaScript, objects and arrays are sent via reference, therefore if the prop is an array or object, changing the object or array inside the child component will impact the parent state, and Vue will not notify you.
As a general guideline, you should avoid altering any prop, including objects and arrays, because this violates one-way data binding and might lead to unexpected effects.
Prop Validation
Components can provide prop requirements, such as the types you've seen thus far. Vue will tell you in the browser's JavaScript console if a condition isn't met. This is very helpful when creating a component that will be utilized by others.
Instead of an array of strings, you can pass an object containing validation criteria to the value of props to provide prop validations. Consider the following scenario:
app.component('my-component', {
props: {
// Basic type validation (values of 'null' and 'undefined' will pass any type validation)
propA: Number,
//There can be multiple possible types
propB: [String, Number],
// Required string
propC: {
type: String,
required: true
},
// Number type with a default value
propD: {
type: Number,
default: 100
},
// Object type with a default value
propE: {
type: Object,
// A factory function must return object or array defaults.
default() {
return { message: 'hello' }
}
},
// Custom validator function
propF: {
validator(value) {
// One of these strings must match the value.
return ['success', 'warning', 'danger'].includes(value)
}
},
// a default value function
propG: {
type: Function,
// This is not a factory function like object or array default; instead, it is a function that serves as a default value.
default() {
return 'Default function'
}
}
}
})
Vue will issue a console warning if prop validation fails (if using the development build).
Note that because props are validated before a component instance is formed, instance properties (such as data, calculated, and so on) will not be available within default or validator functions.
Type Checks
The types in props Vue.js can be one of the following native constructors:
- String
- Number
- Boolean
- Array
- Object
- Date
- Function
- Symbol
In addition, type can be a custom constructor function, and an instanceof check will be used to make the assertion. Given the existence of the constructor function below:
function Person(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
You could use:
app.component('blog-post', {
props: {
author: Person
}
})
To ensure that the author prop's value was created with a new Person.
Prop Casing: camelCase vs kebab-case
Because the names of HTML attributes are case-insensitive, browsers will treat any capital letters as lowercase. That means camelCased prop names must be replaced with their kebab-cased (hyphen-delimited) equivalents when utilizing in-DOM templates:
const app = Vue.createApp({})
app.component('blog-post', {
// camelCase in JavaScript
props: ['postTitle'],
template: '<h3>{{ postTitle }}</h3>'
})
<!-- kebab-case in HTML -->
<blog-post post-title="hello!"></blog-post>
Again, this limitation does not apply if you're using string templates.
FAQs
-
How do you handle props in Vue?
To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
-
What is the use of props in Vue JS?
In Vue, props (or properties), are the way that we pass data from a parent component down to it's child components. When we build our applications out of components, we end up building a data structure called a tree.
-
What is V bind in Vue?
The v-bind directive is a Vue. js directive used to bind one or more attributes, or a component prop to an element. If that attribute is bonded to our data defined in Vue instance then dynamically changes can be observed as data changes.
Key Takeaways
Props and data are two alternative types of storing variables included with Vue.
In Vue, props (or properties) are how we pass data from a parent component down to its child components.
For more Vue.JS related articles, please visit the following links:
- Security in Vue
- Production deployment in Vue
Thanks for choosing us. Happy learning!