0
0
Vueframework~30 mins

Computed properties for derived state in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Computed properties for derived state
📖 Scenario: You are building a simple Vue 3 app that shows a list of products with their prices. You want to display the total price of all products dynamically.
🎯 Goal: Create a Vue 3 component that uses a computed property to calculate the total price from a list of products.
📋 What You'll Learn
Create a reactive list of products with name and price
Add a reactive variable for a discount percentage
Use a computed property to calculate the total price after discount
Display the product names, prices, and the discounted total price
💡 Why This Matters
🌍 Real World
Calculating totals and discounts is common in shopping carts and sales dashboards.
💼 Career
Understanding computed properties is essential for building efficient, reactive Vue applications that update UI automatically.
Progress0 / 4 steps
1
Setup the products list
Create a reactive variable called products using ref that holds an array of objects. Each object should have name and price properties with these exact values: { name: 'Apple', price: 100 }, { name: 'Banana', price: 50 }, and { name: 'Cherry', price: 75 }.
Vue
Need a hint?

Use ref from Vue to create a reactive array named products with the exact objects inside.

2
Add a discount percentage
Create a reactive variable called discount using ref and set it to 10 to represent a 10% discount.
Vue
Need a hint?

Use ref to create a reactive variable named discount and set it to 10.

3
Create a computed property for total price after discount
Import computed from 'vue'. Create a computed property called totalPrice that calculates the sum of all product prices from products.value and then applies the discount percentage from discount.value. Use this formula: sum of prices * (1 - discount / 100).
Vue
Need a hint?

Use computed to create totalPrice. Use reduce on products.value to sum prices, then apply the discount.

4
Display products and total price in template
In the <template>, use a v-for directive to list each product's name and price. Below the list, display the text Total Price after discount: followed by the totalPrice value formatted with toFixed(2).
Vue
Need a hint?

Use v-for to loop over products and show name and price. Then show totalPrice.toFixed(2) below.