Create New Post

Vue.js Conditional Rendering

Vue.js provides several ways to perform conditional rendering, allowing you to display or hide elements based on certain conditions. Here are some common techniques for conditional rendering in Vue.js:

  1. v-if Directive: The v-if directive is used to conditionally render an element. The element will only be rendered if the expression inside the v-if evaluates to true.

    <template>
    <div>
    <p v-if="isConditionTrue">This will be rendered if the condition is true.</p>
    </div>
    </template>

    <script>
    export default {
    data() {
    return {
    isConditionTrue: true
    };
    }
    };
    </script>

  2. v-else Directive: You can use the v-else directive in conjunction with v-if to specify an alternative content to render when the condition is false.

    <template>
    <div>
    <p v-if="isConditionTrue">This will be rendered if the condition is true.</p>
    <p v-else>This will be rendered if the condition is false.</p>
    </div>
    </template>

    <script>
    export default {
    data() {
    return {
    isConditionTrue: false
    };
    }
    };
    </script>

  3. v-else-if Directive: You can also use v-else-if for multiple conditional branches.

    <template>
    <div>
    <p v-if="condition === 'A'">Condition A</p>
    <p v-else-if="condition === 'B'">Condition B</p>
    <p v-else>Default Condition</p>
    </div>
    </template>

    <script>
    export default {
    data() {
    return {
    condition: 'B'
    };
    }
    };
    </script>

  4. Using v-show Directive: The v-show directive is another way to conditionally render elements. The difference is that v-show toggles the visibility of the element with CSS, while v-if actually adds or removes the element from the DOM.

    <template>
    <div>
    <p v-show="isConditionTrue">This will be shown if the condition is true.</p>
    </div>
    </template>

    <script>
    export default {
    data() {
    return {
    isConditionTrue: true
    };
    }
    };
    </script>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

74754