I have this:-
<div class="form-group">
<label for="">Allow Multiple</label>
<select class="form-control" v-model="allowMultiple">
<option value=true>Yes</option>
<option value=false>No</option>
</select>
</div>
I set allowMultiple=true
when I initialize it, but when I select No then allowMultiple='false'
So its no longer a Boolean but a String? How to get it to be Boolean?
In HTML, if you set attribute value in a tag, the value will be default type--string
.So you can use vue v-model
to bind it to other type value, for example, Boolean, Number and etc.
Following code is working, the result is what you want
new Vue({
el:'#app',
data: {
allowMultiple: false
},
methods: {
print: function () {
alert(this.allowMultiple);
}
}
})
<div class="form-group" id='app'>
<label for="">Allow Multiple</label>
<select class="form-control" v-model="allowMultiple" @change='print'>
<option :value='true'>Yes</option>
<option :value='false'>No</option>
</select>
</div>
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
Here is a way to do it in Vue.
Instead of hard coding your options in html. Use the Vue way, set an array of options in your Vue data then use v-for
to render all the options from the array.
Each option should have 2 properties: a text and a value. The value should be the boolean you are looking for.
Now whenever the user changes the selected option, it will always be boolean.
new Vue({
el: '#app',
data: {
allowMultiple: true,
options: [
{text: 'Yes', value: true},
{text: 'No', value: false},
],
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<div class="form-group">
<div>Allow multiple: {{allowMultiple}} [Type: {{typeof allowMultiple}}]</div><br>
<label for="">Allow Multiple</label>
<select class="form-control" v-model="allowMultiple">
<option v-for="option in options" :value="option.value">{{option.text}}</option>
</select>
</div>
</div>
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