View profile

Weekly Vue News - #65 - Share Composable State Across Components

Michael Hoffmann
Michael Hoffmann
Hi 👋
Last week I finally managed to deploy a static version of my portfolio website (developed with Nuxt 3) to Netlify.
This week I’ll work on some bugfixes for CodeSnap.dev and maybe I have time to start writing a new blog post. The next article will be about the Table of Contents component I developed for my portfolio website.
Have a great week ☀️

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:
Image created with CodeSnap.dev
Image created with CodeSnap.dev
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:
Image created with CodeSnap.dev
Image created with CodeSnap.dev
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.
Curated Vue Content
TypeScript Tip: Lock Types Using Const Assertion
When we construct new literal expressions with const assertions, we can signal to the language that
- no literal types in that expression should be widened (e.g. no going from “hello” to string)
- object literals get readonly properties
- array literals become readonly tuples
Image created with CodeSnap.dev
Image created with CodeSnap.dev
Curated Web Development Content
🤣 CSS debugging: The console.log of CSS
Image created with CodeSnap.dev
Image created with CodeSnap.dev
Quote of the Week
Did you enjoy this issue? Yes No
Michael Hoffmann
Michael Hoffmann @mokkapps

This weekly Vue newsletter gives you high-quality tips and curated content to help you become a Vue.js expert.

Additionally, it provides content about web development topics like TypeScript, JavaScript, HTML5, and CSS3.

Published each Monday since June 2021.

In order to unsubscribe, click here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Created with Revue by Twitter.
Holzapfelkreuther Straße 19, 81375 Munich, Germany