vue-multiselect icon indicating copy to clipboard operation
vue-multiselect copied to clipboard

Binding an array of integers as value while having objects for options

Open Iva-rgb opened this issue 3 years ago • 1 comments

As you can see in the fiddle, the idea behind this is:

I need to show the names of the objects as labels in the dropdown but when I make the POST request I only send an array of the IDs chosen in the multiselect.

And of course in the GET request I get an array of IDs (like the variable arrayIntegers in the fiddle).

As you can see there are boxes but no preview, I am aware why this is happening but is there another solution that doesn't involve mapping the array of IDs into objects that fit the multiselect?

Reproduction Link

https://jsfiddle.net/sgp1dfqz/

Expected behaviour

After the GET call the multiselect needs to show the names corresponding to the IDs that are in the returned array.

Iva-rgb avatar Dec 02 '21 14:12 Iva-rgb

Currently, the vue-multiselect doesn't automatically map the array of IDs into objects and you have to do it manually. I think you need to wrap the vue-multiselect into a component to handle the input and output data. We can create a compute with get and set methods and use it as the v-model:

computed: {
    selected: {
        get: function () {
            if (this.arrayIntegers && this.arrayIntegers instanceof Array && this.arrayIntegers.length > 0 &&
            this.options && this.options.length > 0) {
                const selectedValue = this.arrayIntegers.map((item) => {
                    return item.id ? item.id : item;
                });
                
                return this.options.reduce((result, item) => {
                    return selectedValue.includes(item.id) ? [...result, item] : result;
                }, []);
            }
            return this.arrayIntegers;
        },
        set: function (value) {
            this.$emit("input", value.id ? value.id : value);
        }
    }
}

lehoaibaokg avatar Mar 04 '22 15:03 lehoaibaokg

This kind of idea has been mentioned earlier here: #385 .It also has some simple workarounds, so I'm going to close this issue, as its a duplicate. In the meantime you will need to map, or do something similar to your data to make it work

mattelen avatar Aug 26 '22 14:08 mattelen