Vue Props
In Vue, parent components pass data to child components through Props. Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property of that component instance.
Passing Props
Suppose we have a blog post component BlogPost.vue, and we want to pass the post's title to it from the parent component App.vue.
BlogPost.vue (Child Component)
App.vue (Parent Component)
In this example:
- The child component
BlogPost.vueuses thedefineProps(['title'])macro to declare that it receives a prop namedtitle. - The parent component
App.vuepasses a string to thetitleprop when using the<BlogPost>component, similar to passing HTML attributes.
Prop Naming Rules
-
CamelCase vs. kebab-case: In JavaScript, prop names typically use camelCase, like
greetingText. But in HTML attributes, it's recommended to use kebab-case, likegreeting-text. Vue automatically handles the conversion between these two naming styles.
Dynamic Props
Similar to binding normal HTML attributes, we can also use v-bind (or its shorthand :) to dynamically pass props.
Prop Validation
Components can specify validation requirements for props, such as type checking. If the passed value doesn't meet the requirements, Vue will give a warning in the browser console.
To specify validation, you can provide an object with validation requirements to defineProps instead of a string array.
One-Way Data Flow
All props create a one-way down binding between parent and child props: updates from parent props flow down to child components, but not vice versa. This prevents the child component from accidentally mutating the parent component's state, which would make your application's data flow difficult to understand.
Each time the parent component updates, all props in the child component will refresh to the latest values. This means you should not modify a prop inside a child component. If you do this, Vue will give a warning in the console.