javascriptvue.jsprimevue

Can I pre select a value in an PrimeVue Dropdown component?


Case: I am using PrimeVue in a Vue.js project. In this case I have a dropdown, as a component from PrimeVue, which uses an array of objects. The dropdown component looks like this:

<template #position>
    <Dropdown
        class="multiselect-fullsize"
        v-model="selectedFilter[index].pos"
        :options="filterPositions"
        optionLabel="name"
        placeholder="Position" />
    </template>

This dropdown component has a :options property, which refers to the following array:

filterPositions: [
    {"name": "0", "value": "0"},
    {"name": "1", "value": "1"},
    {"name": "2", "value": "2"},
    {"name": "3", "value": "3"},
    {"name": "4", "value": "4"},
    {"name": "5", "value": "5"},
    {"name": "6", "value": "6"},
    {"name": "7", "value": "7"},
    {"name": "8", "value": "8"}
  ]

Question: Is there a way to specify a pre selected item in this dropdown from PrimeVue?

Edit: According to the documentation, there is no property to define a pre selected item. So maybe, if there is a solution, it could be JavaScript only.


Solution

  • The answer is: Yes! The description in the documentation of Dropdown | PrimeVue is a bit confusing, at least for me. The problem is, that it isn´t enough to provide a v-model as I did with v-model="selectedFilter[index].pos", I also have to define optionValue and in my case optionValue="value", because the values in filterPositions have the key value.

    Looks like, if this is set, PrimeVue´s Dropdown is able to check if the v-model matches the optionValue. If not, v-model would be compared to the whole filterPositions item. For example:

    Without optionValue="value":

    {"name": "4", "value": "4"} === 4
    

    With optionValue="value":

    4 === 4
    

    So my Dropdown component in this case have to look like this:

    <Dropdown
        class="multiselect-fullsize"
        v-model="selectedFilter[index].pos"
        :options="filterPositions"
        optionLabel="name"
        optionValue="value"
        placeholder="Position"
    />