简体   繁体   中英

Datalist - how to launch function on click option?

I have a problem with datalist with my input search in VueJS, why when i click with mouse or with enter on one of the option on my datalist , my function getData() which is called to @click and @keypress.enter is not launched?

here is my code:

template:

          <input
            list="data"
            v-model.trim="searchBy"
            @keyup.enter="getAllDatas"
            type="text"
            placeholder="Find more data..."
          />
          <br />
          <datalist id="data">
              <option v-for="r in repos.items" 
                      :key="r.id" 
                      :value="r.name"
                      @click="getData(r.id)"
                      @keypress.enter="getData(r.id)"  />
          </datalist>

script:

 methods: {
    getAllDatas() {
      fetch(`someURL`)
        .then(res => res.json())
        .then(
          res => {
            this.data = res
          }
        )
    },
    ...mapActions(["fetchData"]),
    async getData() {
       await this.fetchData();
  },

i totally have no idea what is wrong here, can someone tell me?

The <datalist> control doesn't have it's own events, you have to use the <input> . Both clicks and keyboard events will trigger the input's keydown listener.

<input
  list="data"
  v-model.trim="searchBy"
  @keydown="getData"
  @keyup.enter="getAllDatas"
  type="text"
  placeholder="Find more data..."
/>

This will pass the event to the handler, so unless you can work around that, you might want to use a <select> instead, or a custom control.

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