Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly apply ternary operator in v-model in vue.js?

I am trying to apply the ternary operator in the v-model but it's not working. I also read a lot of similar questions and answers on StackOverflow but none answer my query.

I have created a data variable testCondition which is set to false by default. Using this condition testCondition?name:place, place is returned in v-model if testCondition is false but if testCondition is true then v-model does not return anything.

Here is my code:

new Vue({
  el: "#app",
  data: {
    name: '',
    place: '',
    testCondition: false,
  },
})
body {
  padding: 15px;
}

input {
  border-radius: 3px;
  padding: 5px;
  border: thin solid lightgrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <br>
  <input type="text" v-model="testCondition?name:place">
  <br><br> Test condition status: {{testCondition}}
  <br> Name: {{name}}
  <br> Place: {{place}}
</div>

Expected result: If I change the value of testCondition from false to true, output should be shown in {{name}}

Actual result: Only working for {{place}} if testCondition is set to false

like image 294
Shubham Pokhriyal Avatar asked Jan 25 '19 13:01

Shubham Pokhriyal


2 Answers

Try this: <input type="text" v-model="$data[testCondition ? 'name' : 'place']">

new Vue({
  el: "#app",
  data: {
    name: '',
    place: '',
    testCondition: false,
  },
})
body {
  padding: 15px;
}

input {
  border-radius: 3px;
  padding: 5px;
  border: thin solid lightgrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <br>
  <input type="text" v-model="$data[testCondition ? 'name' : 'place']">
  <br><br> Test condition status: {{testCondition}}
  <br> Name: {{name}}
  <br> Place: {{place}}
</div>
like image 179
Hammerbot Avatar answered Oct 17 '22 21:10

Hammerbot


You need a computed property with a getter and a setter: https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter

computed: {
  myModel: {
    get() {
      return this.testCondition ? this.name : this.place;
    }
    set(newValue) {
      this.doSomethingWith(newValue);
    }
}
// then in template: v-model="myModel"
like image 9
v-moe Avatar answered Oct 17 '22 23:10

v-moe