0
0
Vueframework~30 mins

Creating a Pinia store in Vue - Try It Yourself

Choose your learning style9 modes available
Creating a Pinia Store
📖 Scenario: You are building a simple Vue 3 app that needs to share a counter value across components. To do this, you will create a Pinia store to hold and manage the counter state.
🎯 Goal: Build a Pinia store named useCounterStore that holds a count state starting at 0, a getter to get the double of count, and an action to increment count by 1.
📋 What You'll Learn
Create a Pinia store using defineStore.
Store must have a state with a count property initialized to 0.
Add a getter named doubleCount that returns count * 2.
Add an action named increment that increases count by 1.
💡 Why This Matters
🌍 Real World
Pinia stores help manage shared state in Vue apps, making it easy to keep data consistent across components.
💼 Career
Understanding Pinia is important for Vue developers to build scalable and maintainable applications.
Progress0 / 4 steps
1
Set up the Pinia store with initial state
Import defineStore from pinia and create a store named useCounterStore with a state function that returns an object with count set to 0.
Vue
Need a hint?

Remember to import defineStore from pinia and define the store with a state function returning an object.

2
Add a getter to compute double the count
Inside the useCounterStore definition, add a getters object with a getter named doubleCount that returns state.count * 2. Use the state parameter in the getter function.
Vue
Need a hint?

Getters are functions inside a getters object. Use state to access the store state.

3
Add an action to increment the count
Inside the useCounterStore definition, add an actions object with a method named increment that increases this.count by 1.
Vue
Need a hint?

Actions are methods inside an actions object. Use this to access and modify state.

4
Export the complete Pinia store
Ensure the useCounterStore is exported as a named export using export const so it can be imported in Vue components.
Vue
Need a hint?

Make sure the store is exported with export const so other files can use it.