簡體   English   中英

Vuejs 從 api 填充選擇選項

[英]Vuejs populate select options from api

我是 VueJs 的初學者,所以我有這個問題

這是我的代碼

<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>

然后我有我的數組

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

然后我使用這個填充這個數組(this.products 是一個從 api 請求填充的數組)

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});
                }
            }
        }
}

使用 console.logs 我可以看到數組已正確填充,但選項沒有

這通常是我從 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>

如果您隨后需要將數據與其他數據相關聯,例如產品列表或其他數據,則始終建議使用計算屬性,以確保數據始終正確一些示例

在Vue的重復中,需要一個key。

v-bind 未設置值。


如果取 {{lots}} 且值正常表達,嘗試修改如下。

<md-option  v-for="(lote, index) of lotes" :value="lote.value" :key="index">{{lote.text}}</md-option>

您只需要綁定選擇選項值屬性

<md-select placeholder="Selection Lote" v-model="selectedLote" name="lotes" id="lotes">
   <md-option  v-for="(lote, index) of lotes" :value="lote.value" :key="index">{{lote.text}}</md-option>
</md-select>

key屬性的詳細使用請參見key API 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM