shentao / vue-multiselect

Universal select/multiselect/tagging component for Vue.js
https://vue-multiselect.js.org/
MIT License
6.69k stars 988 forks source link

Start selection at initial value #1021

Open tim-kilian opened 5 years ago

tim-kilian commented 5 years ago

When I open up the select box I start at the top of the options, even if the selected value is on the bottom. This is an issue when the list of options is very long.

Reproduction Link

https://jsfiddle.net/sadece/6vps23wn/25/

Steps to reproduce

  1. Open reproduction link
  2. See that 40 is selected
  3. Open multiselect
  4. See that selection begins at 0

Expected behaviour

I would expect that the selection starts from 40, else I have to scroll endless to get to my value, if I want to do a slightly change.

Actual behaviour

It starts at the beginning of the list except for the actual selected value.

jaeming commented 4 years ago

For a single select you can do this as a work around for now.

in your component something like this:

    Multiselect(
      ref='select'
      @open='onOpen'
      track-by='id'
      ...
    )

and then handle it like this:

onOpen() {
    const select = this.$refs.select
    let position = select.filteredOptions.findIndex(
      option => option[select.trackBy] === select.value[select.trackBy]
    )
    select.pointerSet(position)
    this.$nextTick(() => {
      select.$refs.list.scrollTop = select.pointerPosition
    })
}

note: I am using an object based options for my list. You need to adjust accordingly if you just have a value. Position would then just be: let position = select.filteredOptions.indexOf(select.value)

Also make sure your optionHeight is correct. If for some reason it has been restyled and is not the default 40, you will need to pass whatever it is with the optionHeight prop.

Also be aware this will scroll to the selection everytime you open, not just on the initial opening, which essentially voids out the default behavior of keeping scroll placement between openings.

here is the previous jsfiddle with adjustment: https://jsfiddle.net/469bsjdq/1/

marcusmoore commented 4 years ago

That worked for me. Thanks @jaeming 😄