可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Can someone help me set the default value for a v-select
? The caveat is that my v-select
is populated with objects, which I think might be the reason why assigning my item-value
to my desired initial value isn't working:
<v-select item-text="name" v-model="defaultSelected" :items="people" > Vue.use(Vuetify); const vm = new Vue({ el: "#app", data: { defaultSelected: { name: "John", last: "Doe" }, people: [ { name: "Harry", last: "Potter" }, { name: "George", last: "Bush" } ] } });
Expected:
The initial v-select
should be John
Actual:
The initial v-select
is blank. Here's a fiddle for reference:
https://jsfiddle.net/tgpfhn8m/734/
Can someone help? Thanks in advance!
回答1:
I believe there are two issues with your set up. Firstly, the initial value should be one of the options
in select
, i.e., you should have people
include your defaultSelected
; Secondly your object needs to contain a value
field, see v-select
props. Otherwise you need to specify item-value
prop; See a working example here.
<v-select item-text="name" item-value="last" v-model="defaultSelected" :items="people" > Vue.use(Vuetify); const vm = new Vue({ el: "#app", data: { defaultSelected: { name: "John", last: "Doe" }, people: [ { name: "John", last: "Doe" }, { name: "Harry", last: "Potter" }, { name: "George", last: "Bush" } ] } });
回答2:
Alternative answer for those finding this question from a search...
How to select default value using an attribute of an object
<template> <v-select v-model="input.user_id" :items="users" item-value="id" item-text="name" label="Users"/> </template> <script> export default { data: () => ({ input: { user_id: 2, }, users: [ { id: 1, name: "John", last: "Doe" }, { id: 2, name: "Harry", last: "Potter" }, { id: 3, name: "George", last: "Bush" } ] }), } </script>
Fiddle example: https://jsfiddle.net/4c3tbj6m/