0
0
Vueframework~30 mins

v-for with v-if precedence in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Using v-for with v-if Precedence in Vue
📖 Scenario: You are building a simple Vue app that shows a list of fruits. You want to display only the fruits that are fresh.
🎯 Goal: Create a Vue component that uses v-for to loop over a list of fruits and uses v-if inside the loop to show only fresh fruits.
📋 What You'll Learn
Create a list of fruits with their freshness status
Add a variable to track the freshness filter
Use v-for to loop over the fruits
Use v-if inside the loop to show only fruits that match the freshness filter
💡 Why This Matters
🌍 Real World
Filtering lists based on user choices is common in shopping sites, dashboards, and apps showing data.
💼 Career
Understanding how to combine v-for and v-if correctly is essential for building dynamic Vue interfaces that respond to user input.
Progress0 / 4 steps
1
Create the fruits list
Create a fruits array in the data() function with these exact objects: { name: 'Apple', fresh: true }, { name: 'Banana', fresh: false }, { name: 'Cherry', fresh: true }.
Vue
Need a hint?

Use ref from Vue to create a reactive array called fruits with the given objects.

2
Add freshness filter variable
Add a showFresh variable using ref and set it to true inside the <script setup>.
Vue
Need a hint?

Use const showFresh = ref(true) to create a reactive boolean variable.

3
Use v-for with v-if inside the template
Inside the <ul>, add a <li> that uses v-for="(fruit, index) in fruits" and inside it use v-if="!showFresh || fruit.fresh" to show only fresh fruits when showFresh is true.
Vue
Need a hint?

Use v-for with (fruit, index) in fruits and add v-if="!showFresh || fruit.fresh" on the same <li> tag.

4
Add a checkbox to toggle freshness filter
Above the <ul>, add an <input type="checkbox"> bound with v-model="showFresh" and a label that says Show only fresh fruits.
Vue
Need a hint?

Use a <label> with an <input type="checkbox" v-model="showFresh"> to toggle the freshness filter.