Reputation: 1216
I have a dropdown with two options: "True" and "False", when selected, I want the form to save the selected value as a boolean.
So if I check the form value when the user has selected "True", I want the value to be true
as a boolean.
<select v-model="selected">
<option :value="null">Pick a value</option>
<option v-for="val in options">{{val}}</option>
</select>
...
data() {
return {
selected: null,
options: ["true", "false"]
}
Here is a fiddle of what I am attempting: https://jsfiddle.net/q0nk9h32/5/
How can I output the selected values in their boolean form?
Bonus question: Instead of having the options
variable, is it valid syntax / good practice, to do:
v-for="val in ["true", "false"]"
?
It seems overkill to have a variable for this (but it fails in fiddle when I try using an array directly). Thanks!
Upvotes: 0
Views: 3106
Reputation: 29092
You can bind a value to each <option>
using :value
.
https://v2.vuejs.org/v2/guide/forms.html#Select-Options
new Vue({
el: '#app',
data() {
return {
selected: null
}
}
});
<script src="https://unpkg.com/vue"></script>
<div id="app">
<select v-model="selected">
<option :value="null">Pick a value</option>
<option v-for="val in [true, false]" :value="val">{{val}}!!!</option>
</select>
<p>
Selected is the {{ typeof selected }}: {{ selected }}
</p>
</div>
You can write the array for a v-for
inline if you want. In your original example it wouldn't have worked because you included double quotes around your strings but were already using double quotes around the attribute.
You've got lots of options for rendering the text as True
and False
for these values...
If you just have two values, true
and false
, I'd be inclined to drop the v-for
altogether and just write them separately.
<option :value="null">Pick a value</option>
<option :value="true">True</option>
<option :value="false">False</option>
Alternative ways of formatting the text would be to use a filter or method. So that's:
<option v-for="val in [true, false]" :value="val">{{ val | filter }}</option>
or
<option v-for="val in [true, false]" :value="val">{{ method(val) }}</option>
For a filter you'd define it in your component's filters
section, for a method it'd be in your methods
. Either way the function just needs to convert the boolean value to a string and then uppercase the first letter.
// Obviously you wouldn't call it 'method'...
method (value) {
const str = String(value);
return str.charAt(0).toUpperCase() + str.slice(1);
}
That said, given there are only two possible options, there are all sorts of other ways to do it. e.g.:
<option v-for="val in [true, false]" :value="val">{{ val ? 'True' : 'False' }}</option>
Upvotes: 2
Reputation: 16
One option would be to create a computed property that just returns this.selected === 'true'.
Upvotes: 0