我试图在 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,这就是为什么您可以看到 @{{}} 而不是 {{}}
答案 0 :(得分:2)
尝试删除 :selected="index === 0"
,在 this.offer.model = this.form.modifications[0];
中,您将传递整个 obj;它应该是 this.offer.model = this.form.modifications[0].value;
答案 1 :(得分:1)
您可以按如下方式设置 created
上的值:
created() {
const { makes = [], modifications = [] } = this.form;
this.offer = {
make: makes[0],
model: modifications.length > 0 ? modifications[0].value : ''
};
}
不需要 :selected="index === 0"