获取 el-select 的 value 和 label 值
在 Element UI 的 el-select 组件中,可以通过以下方法获取选项的 value 和 label 值。
1、绑定 v-model 获取 value
el-select 通常通过 v-model
绑定 value 值,直接访问绑定的变量即可获取当前选中的 value。
<el-select
v-model="company"
@change="companyChange"
clearable
filterable
reserve-keyword
style="width: 300px">
<el-option v-for="item in list" :key="item.id" :label="item.name" :value="item.id"> </el-option>
</el-select>
通过 change 事件获取 label
const list = ref([ { id: '1', name: '选项1' },
{ id: '2', name: '选项2' }
])
const companyChange=(value:string)=> {
console.log(value); // 输出当前选中的 value
var name = list.value.filter(item=>ite.id === value)[0].name // 输出当前选中的label
}
select 初始化
const initSelect=()=>{
// id 为需要选中的选项id
company.value = id
}
2、使用 value-key 获取整个对象
如果选项数据是对象而非简单值,可以设置 value-key
绑定整个对象。
<el-select
v-model="company"
clearable
filterable
@change="changeCompany"
style="width: 300px"
>
<el-option v-for="item in mTenantList" :key="item.tenantId" :label="item.enterpriseName" :value="{value:item.tenantId,label:item.enterpriseName}"> </el-option>
</el-select>
const list = ref([ { id: '1', name: '选项1' },
{ id: '2', name: '选项2' }
])
const companyChange=(value:string,label:string)=> {
console.log(value); // 输出当前选中的 value
console.log(label); // 输出当前选中的 value
}
这里发现初始化问题!无法设置selelct 选中!