Vue js – how to use ternary operator in vue

vue-js-ternary-operator-in-vue-js

In this blog we will learn about how to use the ternary operator in vue js I will show you how to use ternary with v-model in vuejs. we can easily use the ternary operator for conditions in Vue js.

Before moving forward let’s know something about the ternary operator.In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operatorinline if (if), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as “if a then b otherwise c”.

You can read more about the ternary operator from here.

Below is the example, where I am trying to show you how we can use ternary operator in V-model

<!DOCTYPE html>
<html>
<head>
    <title>How to use ternary operator in Vuejs?</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
    
<div id="app">
     
  <input type="text" v-model="$data[myCondition ? 'name' : 'title']">
  <div>Name: {{ name }}</div>
  <div>Title: {{ title }}</div>
   
</div>
    
<script type="text/javascript">
   
    var app = new Vue({
      el: '#app',
      data: {
        name: 'shyam',
        title: 'codehunger',
        myCondition:true
      }
    })
     
</script>
     
</body>
</html>

Below is the example, where I am trying to show you how we can use a ternary operator inside a div or tag.

<!DOCTYPE html>
<html>
<head>
    <title>How to use ternary operator in Vuejs?</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
    
<div id="app">
     
  <div>Name: {{ myVar == 1 ? 'Shyam' : 'Codehunger.com' }}</div>
  
</div>
    
<script type="text/javascript">
   
    var app = new Vue({
      el: '#app',
      data: {
        myVar:1
      }
    })
     
</script>
     
</body>
</html>
5 1 vote
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Spread the love
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x