Explain Vue.js Conditions & Loops

In Vue.js, you can conditionally render elements and iterate over data using directives like v-if, v-else, v-show, and v-for. Let's delve into each aspect with detailed explanations and code examples:

1. Conditional Rendering

Using v-if and v-else

The v-if directive adds or removes an element based on the truthiness of the expression. The v-else directive can be used to render an element if the preceding v-if condition evaluates to false.

<template>
  <div>
    <div v-if="condition">Rendered when condition is true</div>
    <div v-else>Rendered when condition is false</div>
  </div>
</template>

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

Using v-show

The v-show directive toggles the CSS display property of the element based on the truthiness of the expression. The element remains in the DOM, but it's hidden when the expression evaluates to false.

<template>
  <div>
    <div v-show="condition">Rendered when condition is true</div>
  </div>
</template>

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

2. Loops

Looping Over Arrays

The v-for directive allows you to iterate over arrays, rendering a template for each item in the array.

<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: ['Item 1', 'Item 2', 'Item 3']
    };
  }
}
</script>

Looping Over Objects

You can also use v-for to iterate over the properties of an object.

<template>
  <div>
    <ul>
      <li v-for="(value, key) in object" :key="key">{{ key }}: {{ value }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      object: {
        key1: 'Value 1',
        key2: 'Value 2',
        key3: 'Value 3'
      }
    };
  }
}
</script>

These directives provide powerful tools for dynamic rendering and data manipulation in Vue.js templates, enabling you to build complex and interactive user interfaces with ease.

This article on Vue.js Conditions & Loops covers essential concepts for conditionally rendering elements and iterating over data in Vue.js applications. It explains the usage of directives like v-if, v-else, and v-show for conditional rendering, providing examples for each scenario. Additionally, it explores the v-for directive for looping over arrays and objects, demonstrating how to render dynamic content based on data structures. With detailed explanations and code examples, the article equips developers with the knowledge to effectively utilize conditions and loops in Vue.js templates, enhancing the flexibility and interactivity of their applications.