Vue Tip: Share Composable State Across Components
Michael Hoffmann
@mokkapps
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:
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:
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 BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
Vue Tip: Defining and Registering Vue Web Components
Vue Tip: Expose Properties in a Script Setup Component