Props allow components to receive data. They form part of a component's public interface and enable one-way data flow from parent to child.
Written By Joel
Last updated About 1 month ago
Props Declaration
Props are declared in the component options:
defineComponent("my-component", {
props: {
max: 10,
}
});
HTML Props
Just like native Web Components, you can pass props to components via HTML attributes. The only difference is that you use the prop:
prefix.
<my-component prop:max="10"></my-component>
Note: Props are automatically converted to their appropriate types:
Boolean values:
"true"
→true
Numbers:
"123"
→123
Objects/Arrays: Parsed from JSON strings
Strings: Kept as-is
Updating Props
You can access the props of a component instance using the .props
property.
// Set prop value
myComponent.props.max = 20;
Binding Props
You can bind child component props in the parent component setup function. Child components can be queried and controlled just like regular elements using the rq
attribute:
HTML
<rq-parent prop:key="parent">
<my-component rq="child">
<span rq="max-label"></span>
</my-component>
</rq-parent>
JavaScript
// Child component
defineComponent("my-component", {
props: {
max: 10
},
setup(component, props, store) {
component.query("max-label").text(() => props.max);
}
});
// Parent component
defineComponent("rq-parent", {
store: {
config: {
max: 20
}
},
setup(component, props, store) {
// Child prop will update when store.config.max changes
component.query("child")
.bind("prop:max", () => store.config.max);
}
});
One-Way Data Flow
Props are designed to flow data from parent to child. While props can be mutated, it's recommended to treat them as read-only and follow these patterns instead:
A common pattern is to use a prop as an initial value for a store property:
defineComponent("my-component", {
props: {
initialCount: 0
},
store: {
count: 0
},
setup(component, props, store) {
// Initialise store from prop
store.count = props.initialCount;
}
});
Could not load article.
Could not load article.