背景:前端支持利用选择框来支持修改
先来个简单的例子
<template>
<div class="white">
{{value}}<br/>
<el-select v-model="value" value-key="id">
<el-option
v-for="item in options"
:key="item.id"
:label="item.label"
:value="item"
>
</el-option>
</el-select>
</div>
</template>
<script>
export default {
name:'videoDirUploadList',
data(){
return{
options: [{
id:1,
value: 'HTML',
label: 'HTML'
}, {
id:2,
value: 'CSS',
label: 'CSS'
}, {
id:3,
value: 'JavaScript',
label: 'JavaScript'
}],
value: {id:2},
}
},
created() {
},
methods:{
checkChange(){
console.log("change");
}
}
}
</script>
<style>
.white{
background: #fff;
width: 100%;
padding: 10px;
border-radius: 5px;
}
.distribution_box {
display: flex;
justify-content: space-between;
}
.fromData_modify {
width: 780px;
padding: 20px;
text-align: right;
}
</style>
1、如果 Select 的绑定值为对象类型,请务必指定 value-key 作为它的唯一性标识。
这个属性可以把v-model的值和el-option 中的value进行关联起来 这里就是用id关联的
2、所以你看到 value: {id:2}, 就直接绑定到 CSS了
这个场景主要是 后端传了一个数据,然后我们要绑定到el-option上
需求场景
后端传递过来的是一个对象 比如频道 { "id": 46176888, "albumId": xxx, "categoryId": 6, "createdAt": "2023-01-13 14:17:46", "updatedAt": "2023-01-13 14:17:46", "categoryName": "xxx" }
现在要把它绑定到选择el-select控件上,然后el-option是频道表数据
{
"id": 1,
"type": "1",
"name": "电视剧",
"state": 1,
"createdAt": "xxx",
"updatedAt": "xxx"
},
{
"id": 2,
"type": "1",
"name": "电影",
"state": 1,
"createdAt": "xxx",
"updatedAt": "xxx"
},
{
"id": 3,
"type": "1,2",
"name": "动漫",
"state": 1,
"createdAt": "xxx",
"updatedAt": "xxx"
},
首先说下 el-select 中 绑定对象时 value-key 必填 也就是它锁定唯一标示的。这里直接用id,也就是频道表的id来锁定,那么要解决的问题是后端传递的是id和 频道表数据 不一样 ,实际上 categoryId 对应 el-option 的id ,直接用一个中间对象处理即可
比如
albumCategory_={id:albumCategory.categoryId,name:albumCategory.categoryName}
然后绑定albumCategory_ 在添加一个@change 就可以实现需求了