Vue Tip: Share Composable State Across Components
We create a new state on each function call if we define state in a Vue composable. But sometimes, we want to sync the composable state across components.
Let's take a look at a simple example:
We define a simple reactive variable cart
inside the useCart
composable. Every time a component calls useCart
, a new state is created.
The following Stackblitz includes a running demo. Click "Add to cart" on "Component 1" and "Component 2", and you can see that every component has it's own cart
state:
To keep the same state between every useCart
instance, we need to lift he state up outside the function, so it's created only once:
You can test it by yourself in the Stackblitz demo above: Click "Add to shared cart" on "Component 1" and "Component 2", and you can see that they now share the same state.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Expose Properties in a Script Setup Component
Components using script setup are closed by default and will not expose any of the bindings declared inside script setup.
Vue Tip: Defining and Registering Vue Web Components
Web Components is an umbrella term for a set of web native APIs that allows developers to create reusable custom elements. Vue has excellent support for both consuming and creating custom elements.