How to use ternary operator in vue.js?

Member

by jerad , in category: Javascript , 5 months ago

How to use ternary operator in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 5 months ago

@jerad 

In Vue.js, the ternary operator can be used in templates to conditionally render content. Here's an example of how to use the ternary operator in Vue.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<template>
  <div>
    <p>{{ isActive ? 'Active' : 'Inactive' }}</p>
  </div>
</template>

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


In this example, the template will render 'Active' if isActive is true, and 'Inactive' if isActive is false. The ternary operator syntax is condition ? exprIfTrue : exprIfFalse.


You can also use the ternary operator in binding attributes or styles by writing it directly in the template like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<template>
  <div :class="{ 'active': isActive, 'inactive': !isActive }">
    <p>{{ isActive ? 'Active' : 'Inactive' }}</p>
  </div>
</template>

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


In this example, the class active will be added to the div if isActive is true and inactive will be added if isActive is false.