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