Home > Net >  How can I load reactive data to multiselect component?
How can I load reactive data to multiselect component?

Time:10-26

I am trying to use this library https://github.com/vueform/multiselect, but whenever I try to load fetched data, nothing shows up in there, but for e.g when I do {{ testData }} I see the value in html. Can anyone advice me how can I fix this?

Works: <Multiselect :options="['test']" />

Doesn't work:

<Multiselect :options="testData" />

in my setup()

  const testData = computed(() => {
      return [
        {
          name: "Test"
        }
      ]
    })

return { testData }

CodePudding user response:

From the above I assume it should be an array, so try this

 const testData = computed(() => {
      return [{ name: "Test"}]
    })

return { testData }

and add the below change in template

<Multiselect :options="testData" track-by="name" label="name"/>

Modified on request:

If you wanna show the entire object then you can follow the below example

 const testData = computed(() => {
      return [
        { name: 'Vue.js', id: 'vue' },
        { name: 'Angular', id: 'angular' }
      ]
 })

return { testData }

and add a method called nameWithId with the below content. Note: I have given it based on Vue2 syntax, pls change the syntax that matches to Vue3

nameWithId({ name, id }) {
      return `${name} — [${id}]`
    }

then with the below changes in your template

<Multiselect v-model="selectedValue" :options="testData" :custom-label="nameWithId" placeholder="Select one" label="name" track-by="name"/>

Reference doc: https://vue-multiselect.js.org/#sub-getting-started

  • Related