Events let components communicate with their parents. Just like clicking a button triggers a click event, your components can trigger custom events that parents can listen for.
Written By Joel
Last updated About 1 month ago
Emitting Events
Use the emit
method to trigger events from your component:
HTML
<rq-parent prop:key="parent">
<rq-notification prop:key="notification1">
<button rq="close">×</button>
</rq-notification>
</rq-parent>
JavaScript
defineComponent("rq-notification", {
setup(component, props, store) {
component.query("close").on("click", () => {
// Emit a custom event that bubbles up
component.emit("rq-notification:closed");
});
}
});
Listening to Events
Parent components can listen for events using the on
method:
defineComponent("rq-parent", {
setup(component, props, store) {
// Listen for notification events
component.on("rq-notification:closed", () => {
console.log("Notification was closed");
});
}
});
Event Details
Events can carry data through their detail property:
defineComponent("rq-parent", {
setup(component, props, store) {
// Listen for submitted events from any child form
component.on("submitted", (data) => {
console.log("Form submitted at:", data.timestamp);
});
}
});
defineComponent("rq-form", {
setup(component, props, store) {
component.query("submit").on("click", () => {
// Emit event with data
component.emit("submitted", {
username: "john",
timestamp: Date.now()
});
});
}
});
Could not load article.