Home > database >  Vue JS v-select cannot diplaying text from json
Vue JS v-select cannot diplaying text from json

Time:12-29

I have difficulty using vue-select (v-select) when editing data. Currently v-select displays the ID, the data that should appear is the text or label.

enter image description here

const detailPresensi = {
      detail_data: [{
          "id": 3,
          "project_id": 1,
          "duration_minute": 300,
          "detail": "Text 1"
      }, {
          "id": 4,
          "project_id": 2,
          "duration_minute": 203,
          "detail": "Text 2"
      }]
    }

    let options = {
      "1": "AAA",
      "2": "BBB",
      "3": "CCC",
    };

here is the script: enter image description here

Thanks.

CodePudding user response:

Try to add opsi to data and data property need to be a function:

data() {
  return {
    ...,
    opsi: [] 
  }
}

CodePudding user response:

Edited-

I believe you need to fix a few things first-

  1. The opsi property is missing from the data.
  2. The data is not a function.

Now, about your issue that always id is displaying in the selected option, the reason behind this is using reduce prop. It is mentioned in the documentation's section, Caveats with reduce-

The most common issue with reduce is when the component displays your reduced value instead of it's label. This happens when you supply Vue Select a value or v-model binding with a reduced_ value, but the complete option object is not present in the options array.

So, either remove reduce or if wants to continue with the reduce, you need to do the following-

  1. You are using v-select in the loop, which means each v-select should have its own v-model binding, so create a selected variable for each data item and use v-model="item.selected".
  2. To display the respected project id's label, from opsi array, put this in the item's selected variable by default, like this-
detail_data: [{
    "id": 3,
    "project_id": 1,
    "duration_minute": 300,
    "detail": "Text 1",
    "selected": [{
      "id": 1,
      "name": 'AAA'
    }]
  },
  {
    "id": 4,
    "project_id": 2,
    "duration_minute": 203,
    "detail": "Text 2",
    "selected": [{
      "id": 2,
      "name": 'BBB'
    }]
  }
]
  1. Finally, use it in your template like this-
<v-select 
  :options="opsi" 
  :reduce="opsi => opsi.id" 
  label="name"
  v-model="item.selected" 
  :required="!item.project_id"
>
</v-select>

Read more about-

1. Using v-select in the loop.
2. Display selected text using slots.

  • Related