Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs populate select options from api

Im begginer in VueJs so i have this problem

Here my code

<md-select placeholder="Seleccione Lote" v-model="selectedLote" name="lotes" id="lotes">
   <md-option  v-for="lote of lotes" value="lote.value">{{lote.text}}</md-option>
</md-select>

Then i have my array

data: () => ({
        lotes: [],
        selectedLote : null
    })

Then i populate this array using this (this.products is an array populated from an api request)

mounted(){
  this.fillLotesArray();
},
methods:{
fillLotesArray(){
            for(let product of this.products){
                if(this.lotes.findIndex(lote => lote.value === product._source.Lote) === -1){
                    this.lotes.push({value:product._source.Lote, text:product._source.Lote});
                }
            }
        }
}

Using console.logs i can see the array is filled correctly but the options dont

like image 370
Juan Glez Avatar asked Jun 13 '26 18:06

Juan Glez


1 Answers

this is usually my standard way to write a select from an API

<template>
    <select v-model="selectedOption">
        <option v-for="(item, index) in options" :value="item.value" :key="index">{{ item.text }}</option>
    </select>
</template>

<script>
export default {
    name: 'ExampleOptions',
    data() {
        return {
            options: [],
            selectedOption: null,
        };
    },
    mounted() {
        this.loadOptions();
    },
    methods: {
        loadOptions() {
            api.getOptions().then((options) => {
                this.options = options;
            });
        },
    },
};
</script>

if you then need to have the data in correlation to others, such as a list of products or others, it is always advisable to use computed properties, to make sure that the data is always correct some examples

like image 162
Cosimo Chellini Avatar answered Jun 15 '26 08:06

Cosimo Chellini