0
0
Vueframework~30 mins

Getters for computed store values in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Getters for computed store values
📖 Scenario: You are building a simple Vue 3 app to manage a shopping cart. You want to keep track of the items in the cart and show the total price dynamically.
🎯 Goal: Create a Vue 3 store with a list of cart items, add a getter to compute the total price of all items, and use that getter in a component.
📋 What You'll Learn
Create a reactive store with a cartItems array containing objects with name and price.
Add a getter called totalPrice that computes the sum of all item prices.
Use the getter in a Vue component to display the total price.
Follow Vue 3 Composition API and store patterns.
💡 Why This Matters
🌍 Real World
Stores with getters are common in Vue apps to keep data organized and compute values like totals, averages, or filtered lists.
💼 Career
Understanding how to create computed getters in stores and use them in components is essential for building maintainable Vue applications.
Progress0 / 4 steps
1
Create the initial cart items array
Create a reactive store object called store with a property cartItems set to an array containing these exact objects: { name: 'Apple', price: 1.2 }, { name: 'Banana', price: 0.8 }, and { name: 'Cherry', price: 2.5 }.
Vue
Need a hint?

Use an object named store with a property cartItems that is an array of objects.

2
Add a getter for total price
Add a getter property called totalPrice to the store object. This getter should return the sum of the price values of all items in cartItems using reduce.
Vue
Need a hint?

Use a getter with get totalPrice() and inside use this.cartItems.reduce to sum prices.

3
Create a Vue component to display total price
Create a Vue 3 functional component called TotalPriceDisplay that imports store and uses the totalPrice getter to display the total price inside a <div> with the text: Total Price: $ followed by the value.
Vue
Need a hint?

Use defineComponent and return a render function that shows Total Price: $ plus store.totalPrice.

4
Export the store and component
Add export statements to export both the store object and the TotalPriceDisplay component from the module.
Vue
Need a hint?

Use export const before store and TotalPriceDisplay.