Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return boolean and not string when using select?

Tags:

vue.js

vuejs2

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?

like image 246
niko craft Avatar asked Jul 23 '17 12:07

niko craft


2 Answers

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>
like image 61
Kermit Avatar answered Nov 19 '22 21:11

Kermit


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>
like image 6
Ikbel Avatar answered Nov 19 '22 22:11

Ikbel