Vue.js在页面加载后选择与v-model匹配的值,但忽略:selected属性。 代码:
<select class="form-control " :required="true"
:class="{'is-invalid': errors.has('item_'+index) }"
:name="'item_'+index"
v-validate="'required'"
v-model="item.text_value"
v-if="item.type =='TYPE_TEXT' ">
<option
v-for="(itemz, index) in (getwords(item.product_parameter_value.text))"
:value="itemz"
v-bind:selected="index === 0"
>{{ itemz }}</option>
</select>
item.text_value是单个单词(Option2等) getwords(item.product_parameter_value.text)返回数组-['Option1'],['Option2'],['Option3']等。 因此,所选值始终与item.text_value匹配,但不是:selected。 有什么方法可以将选定的值设置为数组中的第一项?
答案 0 :(得分:0)
您应该通过将v-model
设置为正确的值来控制此情况,而不是尝试强制DOM与数据模型不同步。
理想情况下,只需在组件的数据块中设置item.text_value
即可;如果无法提前知道正确的值,则可以在安装组件之前阅读getwords
函数以找到第一个元素:
new Vue({
el: '#app',
data: {
item: {
text_value: "" // ideally you would init the correct value here
}
},
methods: {
getwords() { // simplified stub for your data source:
return ["Option1", "Option2", "Option3"]
}
},
beforeMount() {
// if you can't init it in the data block,
// read the value from getwords() here instead:
this.item.text_value = this.getwords()[0]
}
});
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<select v-model="item.text_value">
<option v-for="itemz, index) in (getwords())" :value="itemz">{{itemz}}</option>
</select>
</div>