Conditional rendering with VDOM
Use v-if, v-else-if, and v-else directives to conditionally render elements and understand how VDOM updates the UI.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Conditional Rendering with VDOM</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<style>
.active {
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<div id="app">
<p v-if="condition === 'A'" class="active">Condition A is true</p>
<p v-else-if="condition === 'B'">Condition B is true</p>
<p v-else>Neither condition A nor B is true</p>
</div>
<script>
new Vue({
el: '#app',
data: {
condition: ''
},
created() {
setTimeout(() => {
this.condition = 'A'; // You can change this value to 'B' or any other value to see the result
}, 1000);
}
});
</script>
</body>
</html>
This HTML file includes Vue.js framework through CDN for the example. The inline CSS styles define a class 'active' to style the paragraph that matches condition A. The HTML body contains a Vue app (#app) with conditional paragraphs. The v-if directive checks if 'condition' matches 'A' and renders the related paragraph. The v-else-if directive checks for 'B' instead. The v-else directive catches all other cases. The Vue instance is initialized with 'condition' data property, which starts as an empty string. The created() lifecycle hook schedules a change in the 'condition' after 1 second using setTimeout, triggering the VDOM to update the rendering accordingly.