简体   繁体   中英

Recognize datalist selection vs. text input in BootstrapVue Autocomplete

Having the following sample code, I want to know the proper event/method to distinguish if the value filled in the input was entered manually or selected from the <datalist> .

TEMPLATE:

<div>
    <b-form-input list="my-list-id"
        v-on:change="handleChange" v-model="sizeSel"/>
    <datalist id="my-list-id">
        <option v-for="size in sizes">{{ size }}</option>
    </datalist>
</div>

JAVASCRIPT:

{
  data() {
    return {
      sizeSel: '',
      sizes: ['Small', 'Medium', 'Large', 'Extra Large']
    }
  },
  watch: {    
  },
  methods: {
    handleChange() {
      alert(this.sizeSel);
    }
  }
}

Use keydown

<datalist> doesn't have its own events but this can be done anyway.

Both keyboard events and <datalist> clicks trigger the input's keydown listener, but only keyboard events have a key property. So if a keydown is triggered having no key property, you know it was a click from the list:

Try this:

 new Vue({ el: "#app", data() { return { sizes: ['Small', 'Medium', 'Large', 'Extra Large'], sizeSel: '', sizeChangedBy: null } }, methods: { onkeydown(e) { const eventSource = e.key? 'input': 'list'; this.sizeChangedBy = eventSource; } }, });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div> Event source: {{ sizeChangedBy }}<br /> <label for="myInput">Choose one:</label> <input list="sizes" id="myInput" name="myInput" v-model="sizeSel" @keydown="onkeydown($event)" /> <datalist id="sizes"> <option v-for="size in sizes":key="size":value="size"></option> </datalist> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM