Vue js ternary operator example

In this article, we will learn Vue js ternary operator. I will show you how to use ternary operator ternary with v-model in Vue js. We can easily use ternary operator for condition in vue js.

The ternary operator in Vue js works the same as in Javascript. It has the syntax: condition ? expression_if_true : expression_if_false.

Here’s how it can be used in Vue component. Let’ see example below.

I will give you two example:

  1. Ternary operator for simple
  2. Ternary operator for v-model
  3. Ternary operator in computed properties
1. Vue js ternary operator for simple
Example
<template>
<div>
<p>{{islogin ? "Welcome, Authentic user" : "Please Log in"}}</p>
</div>
</template>

<script>
export default {
    data() {
        return {
            islogin: false,
        };
    };
};

</script>
2. Vue js ternary operator for v-model
Example
 <div id="app">
      <input type="text" v-model="$data[myCondition ? 'name' : 'title']">
      <div>Name:  {{name}}</div>
      <div>Title:  {{title}}</div>
    </div>

    <script>
      var app = new Vue({
        el: '#app',
        data: {
          name: '',
          title: '',
          myCondition:true
        }
      });
    </script>
3. Vue js ternary operator in computed properties

When ternary logic is more complex, a computed property can help keep your template readable.

Example
<template>
<div>
<p>{{userInformation}}</p>
</div>
</template>

<script>
export default {
    data() {
        return {
            user: {
                role: 'admin',
                isLogin: true
            },
        };
    },
    computed: {
        userInformation() {
            return this.user.isLogin ? `Welcome, ${this.user.role}` : 'Please log in';
        },
    },
};

</script>

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *