0
0
Vueframework~30 mins

Persisting store state in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Persisting store state
📖 Scenario: You are building a simple Vue 3 app that keeps track of a user's favorite color. You want the app to remember the favorite color even if the user refreshes the page or closes and reopens the browser.
🎯 Goal: Create a Vue 3 store using the Composition API that saves the favorite color in localStorage and loads it when the app starts.
📋 What You'll Learn
Create a reactive store object with a favoriteColor property
Add a function to update favoriteColor
Save favoriteColor to localStorage whenever it changes
Load favoriteColor from localStorage when the store initializes
💡 Why This Matters
🌍 Real World
Many web apps need to remember user settings like themes, language, or preferences. Persisting store state with localStorage is a simple way to keep data across sessions.
💼 Career
Understanding how to persist state in frontend frameworks like Vue is essential for building user-friendly, real-world applications that feel seamless and personalized.
Progress0 / 4 steps
1
Create the initial store state
Create a Vue 3 store file named useColorStore.js. Inside it, import ref from vue and create a reactive variable called favoriteColor initialized to the string "blue".
Vue
Need a hint?

Use ref('blue') to create a reactive string variable.

2
Add a function to update the favorite color
Below the favoriteColor variable, add a function called setFavoriteColor that takes a parameter color and sets favoriteColor.value to color.
Vue
Need a hint?

Define a function that changes the reactive variable's value.

3
Save favoriteColor to localStorage when it changes
Import watch from vue. Use watch to observe favoriteColor. Inside the watcher callback, save favoriteColor.value to localStorage with the key "favoriteColor".
Vue
Need a hint?

Use watch to react to changes and save the new value.

4
Load favoriteColor from localStorage on initialization
Before exporting, check if localStorage has a value for the key "favoriteColor". If it exists, set favoriteColor.value to that stored value. Then export favoriteColor and setFavoriteColor from the module.
Vue
Need a hint?

Use localStorage.getItem to load saved data and export the store variables.