0
0
Vueframework~30 mins

Using stores in components in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Using stores in components
📖 Scenario: You are building a simple Vue 3 app that tracks a user's favorite color using a store. The store holds the color value and lets components read and update it.
🎯 Goal: Create a Vue 3 component that uses a store to display and update the favorite color. The component will show the current color and have a button to change it.
📋 What You'll Learn
Create a Pinia store with a state variable favoriteColor set to 'blue'
Add a function in the store called changeColor that sets favoriteColor to 'red'
Create a Vue component that imports and uses the store
Display the current favoriteColor in the component
Add a button in the component that calls changeColor when clicked
💡 Why This Matters
🌍 Real World
Stores help manage shared data in Vue apps, like user preferences or app settings, so components stay in sync easily.
💼 Career
Understanding how to use Pinia stores is important for Vue developers to build scalable and maintainable applications.
Progress0 / 4 steps
1
Create the Pinia store with initial state
Create a Pinia store named useColorStore using defineStore. Inside, define a state with a variable favoriteColor set to the string 'blue'.
Vue
Need a hint?

Use defineStore from Pinia and return an object with favoriteColor set to 'blue' inside state.

2
Add a function to change the color in the store
Inside the useColorStore Pinia store, add an actions section. Define a function called changeColor that sets this.favoriteColor to 'red'.
Vue
Need a hint?

Inside actions, write a function changeColor that updates this.favoriteColor to 'red'.

3
Import and use the store in a Vue component
Create a Vue 3 component using <script setup>. Import useColorStore from the store file. Call useColorStore() and assign it to a constant named colorStore.
Vue
Need a hint?

Use import { useColorStore } from './store' and then call useColorStore() inside <script setup>.

4
Display the color and add a button to change it
In the Vue component template, display the current color using {{ colorStore.favoriteColor }}. Add a button with the text Change Color that calls colorStore.changeColor when clicked.
Vue
Need a hint?

Use mustache syntax to show colorStore.favoriteColor and add a button with @click="colorStore.changeColor".