【问题标题】:Vuejs populate select options from apiVuejs 从 api 填充选择选项
【发布时间】:2021-09-10 09:12:21
【问题描述】:

我是 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 填充这个数组(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 我可以看到数组已正确填充,但选项没有

【问题讨论】:

  • 你可以添加一个 v-if="lotes" 或者你可以让 lotes 成为一个计算属性。
  • this.products是在页面挂载之前还是之后从api请求中填充的?

标签: javascript vue.js materialize


【解决方案1】:

在Vue的重复中,需要一个key。

v-bind 没有设置值。


如果你取 {{lots}} 并且值表示正常,请尝试修改以下内容。

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

【讨论】:

    【解决方案2】:

    你只需要绑定选择选项值属性

    <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属性的详细使用请看keyAPI documentation

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 感谢您的回复,我有相同的代码,但它仍然不适合我
      猜你喜欢
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      • 2018-05-29
      • 2017-12-28
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多