简体   繁体   中英

How to set pre-selected value in vue js dropdownlist

I'm working on two vue component.sending parent component array data to child component using props .now i want to set pre-selected value in child component dropdownlist.

Here is my code sample:

props:{
  // pre-selected value based on this.
  userdata:{
    type:[Array,Object],
    required:true,
  },
  roles:{
    type:[Array,Object],
    required:true,
  },

},

data(){
  return{
   mutableRoles:[],

  }
},

and this is my view part:

//i want set pre-selected value on this dropdownlist
<select multiple v-model="mutableRoles" class="form-control">
         <option v-for="(role,index) in roles" v-bind:value="role.id" >{{role.name}}</option>
       </select>

I have seen many example where show only using string. but in my case both are array.

Try this:

 const CurrentRole = Vue.component("current-role", { template: ` <div> <label>Options</label> <select v-model="roleId" @change="changeValue"> <option v-for="v in roles" :key="v.id" :value="v.id">{{v.title}}</option> </select> </div> `, props: { userdata: { type: [Array, Object], required: true, }, roles: { type: [Array, Object], required: true, } }, data: _ => ({ roleId: null }), methods: { changeValue() { this.userdata.role = this.roles.find(e => e.id == this.roleId) }, }, mounted() { // for initial state this.roleId = this.userdata.role.id }, watch: { userdata(v) { // for changes on parent if (v) this.roleId = v.role.id } } }) new Vue({ el: "#app", data: { rlist: [{ id: 1, title: "a" }, { id: 2, title: "b" }, { id: 3, title: "c" }], user: { role: { id: 3, title: "c" } } }, methods: { changeUser() { this.user = { role: { id: 1, title: "a" } } } } }) 
 <script src="https://unpkg.com/vue@2.5.22/dist/vue.js"></script> <div id="app"> <p>User: {{user}}</p> <current-role :userdata="user" :roles="rlist"> </current-role/> <button @click="changeUser">change user</button> </div> 

The select is tailored for primitive values, therefore you'll need to add helper functions.

Higher level vue frameworks such as vue-material , vuetify , element and muse-ui tend to offer components to cope with such problems with a higher abstraction level.

EDIT:

I changed the snippet in order to make it closer to your situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM