The store option defines a component's internal reactive state. Unlike props, which flow from parent to child, store values can be freely modified within the component.
Written By Joel
Last updated About 1 month ago
Declaring the Store
Store values are declared in the component options:
defineComponent("my-component", {
store: {
count: 0,
message: "Hello",
user: {
name: "John",
age: 25
}
}
});
Accessing the Store
There are two ways to access a component's store:
Setup Function
The setup function receives the store as its third parameter:
defineComponent("rq-counter", {
store: {
count: 0
},
setup(component, props, store) {
// Access store directly in setup
console.log(store.count) // 0
// Modifying state
component.query("button").on("click", () => {
store.count++
})
}
})
Component Instance
There are several ways to access component instances and their stores:
Query Component
Use queryComponent
to access components that aren't directly related (not parents, children, or siblings):
// Query first instance
const sidebar = queryComponent("rq-sidebar");
sidebar.store.isCollapsed = true;
// Query specific instance by key
const modal = queryComponent("rq-modal", "onboarding");
modal.store.isOpen = true;
This is useful for global components like modals, notifications, or navigation elements that need to be controlled from anywhere in the application.
Child Components
You can access child components using the .components
map available on a component instance.
defineComponent("parent", {
setup(component, props, store) {
// Access child component by key
const child = component.components.get("my-component");
console.log(child.store);
}
});
Parent Component
While you can access the parent component's store directly, props for parent-to-child communication are recommended to maintain clear data flow in your application.
defineComponent("my-component", {
setup(component, props, store) {
// Access parent component's store
console.log(component.parent.store);
}
});
Note
For more information about reactivity and how state updates trigger changes, see the
Could not load article.
guide.Could not load article.
Could not load article.