Conditional Rendering with v-if and the Virtual DOM
Provide an example of how to conditionally render elements with v-if in Vue.js and discuss the impact on the VDOM.
<div id='conditional-rendering-example'>
<h1 v-if='showTitle'>Hello, Vue!</h1>
<p v-else>No title to display</p>
</div>
This is the HTML template with Vue directives. If 'showTitle' is truthy, a heading element displaying 'Hello, Vue!' is rendered. Otherwise, a paragraph with the text 'No title to display' is shown.
<script src='https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js'></script>
<script>
new Vue({
el: '#conditional-rendering-example',
data: {
showTitle: true
}
});
</script>
This JavaScript code initializes a Vue instance, binding it to the div with id 'conditional-rendering-example'. It sets up a reactive data property 'showTitle' that controls the conditional rendering.
body {
font-family: Arial, sans-serif;
}
This is a simple CSS rule to set the font style for the body of the document.