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’s 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.

Jasminkumar Borad
Jasminkumar Borad

I'm a full-stack developer, enterpreneur and owner of webstuffsolution.com. I live in india and i like to write tutorial and tips that can help to other user. I like to share various programming language tips and solution. I believe in hardworking and consistency.

Leave a Reply

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