gpt4 book ai didi

javascript - 如何在vue js下拉列表中设置预选值

转载 作者:搜寻专家 更新时间:2023-10-30 22:50:05 26 4
gpt4 key购买 nike

我正在处理两个 vue 组件。使用 parent 组件 array 数据发送到 child 组件 props。现在我想在 child 组件下拉列表中设置 pre-selected 值。

这是我的代码示例:

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

},

data(){
return{
mutableRoles:[],

}
},

这是我的观点:

//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.

最佳答案

试试这个:

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>

select 是为原始值量身定制的,因此您需要添加辅助函数。

更高级别的 vue 框架,例如 vue-material , vuetify , elementmuse-ui倾向于提供组件来处理具有更高抽象级别的此类问题。

编辑:

我更改了代码段以使其更接近您的情况。

关于javascript - 如何在vue js下拉列表中设置预选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54380234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com