Vue实现Element UI的下拉框默认选中,值来自父组件或异步获取
程序员文章站
2024-01-02 22:53:28
...
子组件使用watch监听父组件传过来的值,并且赋值给子组件的data参数。
1、父组件传了一个userId属性给子组件
<Children
@searchForm="searchForm"
:memberList="memberList"
:userId="userId"
/>
export default {
data: () => ({
memberList: [
{
userId: 1,
userName: "Vegeta"
},
{
userId: 2,
userName: "Ategev"
}],
userId: "1"
})
}
2、Element UI添加下拉框组件,并赋值遍历
<el-form-item label="负责人:">
<el-select
v-model="form.supporterId"
>
<el-option
v-for="item in memberList"
:key="item.userId"
:label="item.userName + '/' + item.userId"
:value="item.userId"
></el-option>
</el-select>
</el-form-item>
3、子组件使用props接收父组件传过来的userId与memberList
props: ["memberList", "userId"],
data: () => ({
form: {
supporterId: ""
}
}),
created() {
//this.getSupporterId(name);
},
methods() {
/**async getSupporterId(name) {
const rs = await this.$http.getSupporterId("AtegeV");
if (rs.success) {
this.form.supporterId = rs.data;//this.form.supporterId = 2
} else {
this.$message({
message: rs.msg,
type: "warning",
});
}
}*/
}
4、子组件监听userId的值,当它由空转变时就会触发,这时候就能取到了,拿到值后要做的处理方法也需要在watch中执行
watch: {
userId: function(newVal, oldVal) {
this.form.supporterId = newVal;//this.form.supporterId = 2
}
}
参考: