PASSWORD RESET

Your destination for complete Tech news

Vue

How to use the ternary operator in Vue?

1.59K 0
< 1 min read

You can use the ternary operator in Vue to conditionally render elements or bind data properties. The ternary operator is a shorthand version of an if-else statement that allows you to evaluate a condition and return one of two values based on the result of that evaluation.

Here’s an example of using the ternary operator to conditionally render an element in Vue:

<template>
  <div>
    <p v-if="isTrue">True</p>
    <p v-else>False</p>
  </div>
</template>

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

In this example, we have two paragraphs. The v-if directive evaluates the value of the isTrue data property. If isTrue is true, the first paragraph will be rendered. If isTrue is false, the second paragraph will be rendered.

Here’s an example of using the ternary operator to bind a data property in Vue:

<template>
  <div>
    <p :class="isActive ? 'active' : ''">Active</p>
  </div>
</template>

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

In this example, we have a paragraph that has a dynamic class binding using the :class directive. The isActive data property is evaluated, and if it’s true, the active class is applied to the paragraph. If it’s false, no class is applied.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.