admin管理员组文章数量:1180542
The :selected
prop is not selecting the target option
in Vue2 when i use v-model
for select
:
Template
...
<select v-model="form.item">
<option :value="item.id" v-for="(item, index) in items" :selected="item.status == 2">{{ item.name }}</option>
</select>
...
Script
data: function () {
return {
items: [{id:1, name: "foo", status: 1},{id: 3, name: "bar", status: 2}],
form: {item: null}
}
}
In this case , after mounted there is no selected option.
How can i fix this?
Note
When i remove v-model
it works fine (target option
is selected by default) but i don't have the value of the selected option
in form.item
The :selected
prop is not selecting the target option
in Vue2 when i use v-model
for select
:
Template
...
<select v-model="form.item">
<option :value="item.id" v-for="(item, index) in items" :selected="item.status == 2">{{ item.name }}</option>
</select>
...
Script
data: function () {
return {
items: [{id:1, name: "foo", status: 1},{id: 3, name: "bar", status: 2}],
form: {item: null}
}
}
In this case , after mounted there is no selected option.
How can i fix this?
Note
When i remove v-model
it works fine (target option
is selected by default) but i don't have the value of the selected option
in form.item
- 1 v-model and :selected don't work together. It is explained in the official doc. You can only use one of both. – hannes neukermans Commented Oct 16, 2017 at 14:06
- @hannesneukermans do you know any good solution for this? – Saeed Vaziry Commented Oct 16, 2017 at 14:16
3 Answers
Reset to default 27v-model will ignore the initial value, checked or selected attributes. found on any form elements
The solution is to remove :selected binding. and use data props to bind to v-model
<select v-model="form.selectedItem">
<option :value="item.id" v-for="(item, index) in items">{{ item.name }}
</option>
</select>
declare vue instance as
data() {
return {
selectedItem: 2
}
}
link to official documentation
Another solution is by using $refs
instead of v-model.
<select ref="selectedItem">
<option v-for="(item, index) in items" :value="item.id" :selected="item.status == 2">
{{ item.name }}
</option>
</select>
Then to get the value of the selected item, call...
this.$refs.selectedItem.value
<select v-model="selectedGroup">
<option :value="false" :selected="selectedGroup == false">All</option>
<option v-if="organization.groups" v-for="group in organization.groups" :value="group">{{ group }}</option>
</select>
本文标签: javascriptVue selected prop not working with vmodelStack Overflow
版权声明:本文标题:javascript - Vue selected prop not working with v-model - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738179410a2067410.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论