vue.jsvuejs2

How to return boolean and not string when using select?


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?


Solution

  • In HTML, if you set attribute value in a tag, the value will be default type--string.So you can use vue v-model in combination with :value 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>
        Type: {{ typeof allowMultiple }},
        Value: {{ allowMultiple }} 
    </div>
    
    </div>
    <script src="https://unpkg.com/vue@2.4.2/dist/vue.min.js"></script>