0
0
Vueframework~30 mins

JavaScript expressions in templates in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
JavaScript expressions in templates
📖 Scenario: You are building a simple Vue 3 app that shows a list of products with their prices and discounts. You want to display the final price after applying the discount using JavaScript expressions directly inside the template.
🎯 Goal: Create a Vue 3 component that uses JavaScript expressions inside the template to calculate and display the discounted price for each product.
📋 What You'll Learn
Create a reactive array of products with name, price, and discount percentage
Add a variable for a minimum discount threshold
Use JavaScript expressions in the template to calculate the discounted price only for products with discount above the threshold
Display the product name and the calculated discounted price in the template
💡 Why This Matters
🌍 Real World
Using JavaScript expressions in templates is common when you want to show dynamic values based on data without writing extra methods or computed properties.
💼 Career
Front-end developers often need to display calculated values in UI frameworks like Vue. Understanding expressions in templates helps build interactive and efficient user interfaces.
Progress0 / 4 steps
1
Setup the products data
Create a reactive array called products with these exact objects: { name: 'Shoes', price: 100, discount: 10 }, { name: 'Hat', price: 50, discount: 5 }, and { name: 'Jacket', price: 200, discount: 20 } inside the <script setup> block.
Vue
Need a hint?

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

2
Add a discount threshold variable
Inside the <script setup> block, create a constant called minDiscount and set it to 10.
Vue
Need a hint?

Just add const minDiscount = 10 inside the <script setup> block.

3
Use JavaScript expressions in the template
In the <template>, use a v-for directive with product and index to loop over products. Inside the loop, display the product's name and the discounted price calculated as product.price * (1 - product.discount / 100) only if product.discount is greater than or equal to minDiscount. Use a JavaScript expression with a ternary operator to show the discounted price or the original price accordingly.
Vue
Need a hint?

Use v-for="(product, index) in products" and inside double curly braces use a ternary expression to calculate the discounted price or show original price.

4
Add accessibility and final touches
Add a role="list" attribute to the <ul> element and a role="listitem" attribute to each <li> element for accessibility. Also, add a class="product-list" to the <ul> and class="product-item" to each <li>.
Vue
Need a hint?

Add role="list" and class="product-list" to the <ul>. Add role="listitem" and class="product-item" to each <li>.