【问题标题】:How to select the first option in a select as default in Vue3?如何选择选择中的第一个选项作为Vue3中的默认选项?
【发布时间】:2021-07-18 21:01:24
【问题描述】:

我试图在 Vue 3 中填充选择时选择第一个选项。我已阅读 this question 但没有一个答案对我有用。

这是我的代码

js:

const newOfferApp = createApp({
    data() {
        return {
            message: "Ok vue is working ... ",
            form: {
                modifications: [],
                makes: ["Abarth", "AC", "Acura", "Aixam"],
            },
            offer: {
                model: '',
                make: ''
            }
        }
    },
    methods: {
        fetchModification() {
            this.form.modifications =
                [
                    {key: "0", value: "MDX"},
                    {key: "1", value: "NSX"},
                    {key: "2", value: "RL"}
                ]

            this.offer.model = this.form.modifications[0];
        }
    }
});

html:

<div class="col-sm-12 col-md-6 col-lg-6">
   <label for="make" class="form-label">{{ __('new.make') }}</label>
   <select v-model="offer.make" @change="fetchModification"
      class="form-control"
      id="make"
      name="make">
      <option v-for="(make,i) in form.makes" :value="make" :selected="i === 0">
         @{{make}}
      </option>
   </select>
</div>


<div class="col-sm-12 col-md-6 col-lg-6">
   <label for="modification" class="form-label">{{ __('new.model') }}</label>
   <select v-model="offer.model"
      name="id"
      class="form-control"
      id="modification">
      <option v-for="(mod,index) in form.modifications " :key="mod.value" :value="mod.value"
         :selected="index === 0">
         @{{ mod.value }}
      </option>
   </select>
   <div class="invalid-feedback">
   </div>
</div>

注意:我使用的是 Laravel,这就是为什么你可以看到 @{{}} 而不是 {{}}

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    尝试删除:selected="index === 0",并在 this.offer.model = this.form.modifications[0]; 中传递整个obj;应该是this.offer.model = this.form.modifications[0].value;

    【讨论】:

      【解决方案2】:

      您可以在created 上设置值,如下所示:

      created() {
        const { makes = [], modifications = [] } = this.form;
        this.offer = { 
          make:  makes[0], 
          model: modifications.length > 0 ? modifications[0].value : ''
        }; 
      }
      

      不需要:selected="index === 0"

      【讨论】:

        猜你喜欢
        • 2022-01-06
        • 1970-01-01
        • 2021-03-21
        • 1970-01-01
        • 2020-10-18
        • 2023-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多