Passing Data from Parent to Child Components
# Passing Data from Parent to Child Components
In the parent component, pass values to the child component by binding attributes with v-bind on the child component tag:
<ComponentName v-bind:name="value"></ComponentName>
Without v-bind, the passed value is a string literal. With v-bind binding, the passed value is an expression. In the child component, receive the values through the props object:
props: {
name: { // receive the value passed from the parent
type: String || ...,
default: ''
}
}
2
3
4
5
6
# One-Way Data Flow
All props form a one-way-down binding between the child and parent: when the parent prop updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent's state, which would make the data flow of your application difficult to understand.
Child components cannot directly modify values passed from the parent
There are two common cases where you might be tempted to mutate a prop:
- The prop is used to pass an initial value; the child component wants to use it as a local data property. In this case, it's best to define a local data property that uses the prop as its initial value:
props: ['initialCounter'],
data: function () {
return {
counter: this.initialCounter
}
}
2
3
4
5
6
- The prop is passed in as a raw value that needs to be transformed. In this case, it's best to define a computed property using the prop's value:
props: ['size'],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}
2
3
4
5
6