You are currently viewing Conditional Rendering in Vuejs: v-if, v-show, and v-else

Conditional Rendering in Vuejs: v-if, v-show, and v-else

Conditional rendering is a powerful feature in Vue.js that allows developers to dynamically control the visibility of elements based on the application’s state. This capability is essential for creating interactive user interfaces that respond to user input and other events. Vue.js provides several directives for conditional rendering, including v-if, v-show, and v-else.

The v-if directive conditionally renders an element based on the truthiness of an expression, meaning the element is added or removed from the DOM. The v-show directive, on the other hand, toggles the visibility of an element using CSS, meaning the element remains in the DOM but is hidden or shown based on an expression. The v-else directive works in conjunction with v-if to provide an alternative block of content if the v-if condition evaluates to false. Understanding how to use these directives effectively can significantly enhance the interactivity and performance of your Vue.js applications.

v-if: Conditional Rendering

Basic Usage

The v-if directive is used to conditionally render elements based on the value of a data property. If the condition evaluates to true, the element is rendered; otherwise, it is not included in the DOM.

Here’s an example of using v-if:

<template>

  <div>
    <button @click="toggle">Toggle Message</button>
    <p v-if="isVisible">Hello, Vue.js!</p>
  </div>
  
</template>

<script>

export default {

  data() {
    return {
      isVisible: true
    };
  },
  
  methods: {
    toggle() {
      this.isVisible = !this.isVisible;
    }
  }
};

</script>

In this example, the p element is conditionally rendered based on the value of isVisible. Clicking the button toggles the visibility of the message.

v-else and v-else-if

The v-else directive provides an alternative block of content to render if the v-if condition evaluates to false. The v-else-if directive allows you to chain multiple conditional blocks.

Here’s an example of using v-else and v-else-if:

<template>

  <div>
    <button @click="toggle">Toggle Status</button>
    <p v-if="status === 'active'">Status: Active</p>
    <p v-else-if="status === 'inactive'">Status: Inactive</p>
    <p v-else>Status: Unknown</p>
  </div>
  
</template>

<script>

export default {

  data() {
    return {
      status: 'active'
    };
  },
  
  methods: {
  
    toggle() {
	
      if (this.status === 'active') {
        this.status = 'inactive';
      } else if (this.status === 'inactive') {
        this.status = 'unknown';
      } else {
        this.status = 'active';
      }
	  
    }
  }
};

</script>

In this example, the paragraph displayed depends on the value of the status data property, demonstrating how to use v-if, v-else-if, and v-else together.

v-show: Toggling Visibility

Basic Usage

The v-show directive toggles the visibility of an element based on the value of a data property. Unlike v-if, v-show does not remove the element from the DOM; it simply applies CSS to hide or show the element.

Here’s an example of using v-show:

<template>

  <div>
    <button @click="toggle">Toggle Message</button>
    <p v-show="isVisible">Hello, Vue.js!</p>
  </div>
  
</template>

<script>

export default {

  data() {
    return {
      isVisible: true
    };
  },
  
  methods: {
    toggle() {
      this.isVisible = !this.isVisible;
    }
  }
  
};

</script>

In this example, the p element’s visibility is toggled using v-show. Clicking the button hides or shows the message without removing it from the DOM.

Comparison with v-if

The primary difference between v-if and v-show is that v-if conditionally renders elements by adding or removing them from the DOM, whereas v-show toggles the visibility of elements using CSS. Use v-if when the condition is unlikely to change frequently, as it avoids the performance cost of frequently adding or removing elements. Use v-show when you need to toggle visibility frequently, as it avoids the cost of re-rendering elements.

Here’s a comparison example:

<template>

  <div>
    <button @click="toggle">Toggle Messages</button>
    <p v-if="isVisible">This is rendered with v-if.</p>
    <p v-show="isVisible">This is toggled with v-show.</p>
  </div>
  
</template>

<script>

export default {

  data() {
    return {
      isVisible: true
    };
  },
  
  methods: {
    toggle() {
      this.isVisible = !this.isVisible;
    }
  }
};

</script>

In this example, one message is conditionally rendered using v-if, and the other is toggled using v-show. Toggling isVisible will show or hide both messages, but the v-if message is added or removed from the DOM, while the v-show message remains in the DOM and is only hidden or shown.

Combining v-if and v-show

In some scenarios, you might want to use both v-if and v-show to take advantage of their respective strengths. For instance, you might use v-if to render an element only if a certain condition is met initially, and then use v-show to toggle its visibility based on user interactions.

Here’s an example of combining v-if and v-show:

<template>

  <div>
    <button @click="toggleVisibility">Toggle Element</button>
    <p v-if="shouldRender" v-show="isVisible">This element is conditionally rendered and toggled.</p>
  </div>
  
</template>

<script>

export default {

  data() {
  
    return {
      shouldRender: true,
      isVisible: true
    };
	
  },
  
  methods: {
  
    toggleVisibility() {
      this.isVisible = !this.isVisible;
    }
	
  }
  
};

</script>

In this example, the paragraph element is initially rendered based on shouldRender, and its visibility is toggled using v-show. This approach ensures the element is rendered only if necessary, and its visibility can be efficiently toggled.

Best Practices for Conditional Rendering

When using conditional rendering in Vue.js, consider the following best practices:

  • Minimize DOM Updates: Use v-if to avoid unnecessary DOM updates for elements that are not always needed. For frequently toggled elements, prefer v-show to reduce the performance cost of adding and removing elements from the DOM.
  • Avoid Overuse of v-if: Avoid using multiple v-if conditions in a template. Instead, use computed properties or methods to handle complex conditional logic.
  • Use Key Attribute with v-if: When using v-if in a v-for loop, always use the key attribute to help Vue identify elements and optimize re-rendering.
  • Keep Templates Clean: For complex conditions, consider using computed properties or methods to keep your templates clean and readable.

Here’s an example of using a computed property for complex conditions:

<template>

  <div>
    <p v-if="isEligible">You are eligible for this offer.</p>
  </div>
  
</template>

<script>

export default {

  data() {
  
    return {
      age: 25,
      member: true
    };
	
  },
  
  computed: {
  
    isEligible() {
      return this.age > 18 && this.member;
    }
	
  }
  
};

</script>

In this example, the computed property isEligible encapsulates the complex condition, making the template more readable.

Conclusion

Conditional rendering is a fundamental feature in Vue.js that allows developers to create dynamic and interactive user interfaces. By understanding and effectively using v-if, v-show, and v-else, you can control the visibility of elements based on your application’s state. Combining these directives with best practices ensures efficient and maintainable code.

Additional Resources

To further expand your knowledge of conditional rendering in Vue.js, here are some additional resources:

  • Vue.js Documentation: The official Vue.js documentation is a comprehensive resource for understanding the framework’s capabilities and usage. Vue.js Documentation
  • Vue Mastery: An excellent platform offering tutorials and courses on Vue.js. Vue Mastery
  • Vue School: Another great resource for learning Vue.js through video courses. Vue School
  • Books: Books such as “The Majesty of Vue.js” by Alex Kyriakidis and Kostas Maniatis provide in-depth insights and practical examples.
  • Community and Forums: Join online communities and forums like Vue Forum, Reddit, and Stack Overflow to connect with other Vue developers, ask questions, and share knowledge.

By leveraging these resources and continuously practicing, you’ll become proficient in using conditional rendering in Vue.js and be well on your way to developing impressive and functional web applications.

Leave a Reply