Javascript is required
Mokkapps Logo

Vue Tip: Share Composable State Across Components

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Oct 28, 2022
1 min read
|
34 views
Composables
Share Composable State Across Components Image

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:

useCart.ts
import { Ref, ref } from 'vue'const useCart = () => {  const cart: Ref<Record<string, number>> = ref({})  const addToCart = (key: string, value: number) => {    cart.value[key] = value  }  return {    cart,    addToCart,  }}export default useCart

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:

useCart.ts
import { Ref, ref } from 'vue'const cart: Ref<Record<string, number>> = ref({})const useCart = () => {  const addToCart = (key: string, value: number) => {    cart.value[key] = value  }  return {    cart,    addToCart,  }}export default useCart

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 Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.