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
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>
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With