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.