Vue 2: Toggle Visibility Lab
Objective
In this lab, you will build a simple Vue 2 application that toggles the visibility of two div
elements using the v-if
directive.
Prerequisites
- Basic knowledge of HTML, CSS, and JavaScript
- Familiarity with Vue 2
Step 1: Use v-if
for Conditional Rendering
Inside your App.vue
's <script>
section, add a data
property named isVisible
and set it to true
. Use the v-if
directive to conditionally render your divs based on the isVisible
state.
<script> export default { data() { return { isVisible: true, }; }, }; </script>
Update your div
elements to include v-if
:
<div id="div1" v-if="isVisible"> This is Div 1 </div> <div id="div2" v-if="!isVisible"> This is Div 2 </div>
Step 2: Implement a Toggle Button
Finally, add a button element that toggles the isVisible
state when clicked. Use Vue's @click
directive to update isVisible
.
<button @click="isVisible = !isVisible">Toggle Divs</button>
Challenges Information
Challenge 1: Create Initial Div with ID 'div1'
Your task is to create a div
element with an id
of div1
. This div should be visible initially and should contain the exact text 'first div'.
Challenge 2: Create Second Div with ID 'div2'
Create a div
element with an id
of div2
. This div should also be visible initially and must contain the exact text 'second div'.
Challenge 3: Create Toggle Button for First Div
Create a button
element with an id
of toggle-first-div
. This button will be used to toggle the visibility of div1
.
Challenge 4: Create Toggle Button for Second Div
Create another button
element with an id
of toggle-second-div
. This button will be used to toggle the visibility of div2
.
Challenge 5: Implement Toggle Functionality for div1
Attach a Vue event handler to the button with id
toggle-first-div
. Clicking this button should toggle the visibility of div1
. Note that you should use Vue's v-if
directive to toggle visibility. When clicked for the first time, div1
should be unmounted from the DOM.
Challenge 6: Implement Toggle Functionality for div2
Attach a Vue event handler to the button with id
toggle-second-div
. Clicking this button should toggle the visibility of div2
. Use Vue's v-if
directive for this. When clicked for the first time, div2
should be unmounted from the DOM.