JavaScriptUncategorizedVue js

Vue js – how to use ternary operator in vue

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>

Related Articles

Leave a Reply

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

Check Also
Close
Back to top button

Adblock Detected

Please consider supporting us by disabling your ad blocker