vue之elementUi的el-select同時(shí)獲取value和label的三種方式
目錄
- 一. 需求
- 二. 方法
- 1. 通過ref的形式(推薦)
- 2. 通過字符串拼接的形式(推薦)
- 3. 通過遍歷的形式(不推薦)
- 總結(jié)
一. 需求
如下圖的下拉選項(xiàng)框,點(diǎn)擊查看需要同時(shí)獲取到選中選項(xiàng)的label值以及value值
以下是vue的渲染,在此不做過多介紹
<template> <div> <el-select ref="optionRef" v-model="value" placeholder="請(qǐng)選擇" > <el-optionv-for="item in options":key="item.id":label="item.label":value="item.value" > </el-option> </el-select> <el-button @click="showoptions" type="primary" >查看</el-button > </div></template>
el-select綁定一個(gè)value值,el-option需要一個(gè)數(shù)組,以下是模擬數(shù)據(jù)
data() { return { value: "", options: [{ id: 0, label: "蘋果", value: "apple" },{ id: 1, label: "香蕉", value: "banana" },{ id: 2, label: "橙子", value: "orange" }, ], }; },
二. 方法
1. 通過ref的形式(推薦)
在進(jìn)行el-select渲染時(shí),給el-select添加一個(gè)ref,用于獲取值
然后就可以在點(diǎn)擊事件或者提交表單時(shí)獲取到選中的值了
methods: { showoptions() { console.log(this.$refs.optionRef.selected.value,this.$refs.optionRef.selected.label ); }, },
想要回顯的話直接給定el-select綁定的value為某個(gè)值即可,如想要回顯蘋果,就賦值為apple
該方法完整代碼如下:
<template> <div> <el-select ref="optionRef" v-model="value" placeholder="請(qǐng)選擇" > <el-optionv-for="item in options":key="item.id":label="item.label":value="item.value" > </el-option> </el-select> <el-button @click="showoptions" type="primary" >查看</el-button > </div></template><script>export default { data() { return { value: "", options: [{ id: 0, label: "蘋果", value: "apple" },{ id: 1, label: "香蕉", value: "banana" },{ id: 2, label: "橙子", value: "orange" }, ], }; }, methods: { showoptions() { console.log(this.$refs.optionRef.selected.value,this.$refs.optionRef.selected.label ); }, },};</script>
2. 通過字符串拼接的形式(推薦)
這個(gè)方法相對(duì)于第一種方法而已,優(yōu)點(diǎn)在于不止于同時(shí)獲取label和value,可以獲取多個(gè),如再加一個(gè)id值什么的,這里演示還是以獲取label和value為例,如想要獲取其他,按照如下方式即可
我們?cè)趀l-option渲染時(shí),所設(shè)置的value屬性值可以設(shè)置成label+value的形式,如下圖
那么我們獲取值時(shí),直接獲取el-select綁定的value即可,
獲取后的值形式如下圖,那么+號(hào)前面的就是想要的value值,后面的就是label值了,對(duì)返回的數(shù)據(jù)用split('+')進(jìn)行切割,返回的數(shù)組索引0就是value值,數(shù)組索引1就是label值
這種方法在回顯的時(shí)候稍微有點(diǎn)麻煩,因?yàn)橐鸦仫@的值也弄成value+label的形式渲染到el-select所綁定的value上,比如要回顯香蕉,就將value設(shè)置為’banana+香蕉‘
以下是第二種方法的完整代碼
<template> <div> <el-select ref="optionRef" v-model="value" placeholder="請(qǐng)選擇" > <el-optionv-for="item in options":key="item.id":label="item.label":value="item.value + "+" + item.label" > </el-option> </el-select> <el-button @click="showoptions" type="primary" >查看</el-button > </div></template><script>export default { data() { return { value: "banana+香蕉", options: [{ id: 0, label: "蘋果", value: "apple" },{ id: 1, label: "香蕉", value: "banana" },{ id: 2, label: "橙子", value: "orange" }, ], }; }, methods: { showoptions() { console.log(this.value); console.log("value=====", this.value.split("+")[0]); console.log("label=====", this.value.split("+")[1]); }, },};</script>
3. 通過遍歷的形式(不推薦)
這種方法就不太友好,就是通過el-select綁定的value對(duì)el-option數(shù)組進(jìn)行遍歷查找
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持。
相關(guān)文章:
