首页 > 解决方案 > Vuejs 从 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 我可以看到数组已正确填充,但选项没有

标签: javascriptvue.jsmaterialize

解决方案


这通常是我从 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>

如果您随后需要将数据与其他数据相关联,例如产品列表或其他数据,则始终建议使用计算属性,以确保数据始终正确 一些示例


推荐阅读