需求:
- 頁面中使用下拉框,顯示多列內容”
- 提交數據時,是item數據中的其中某個字段
- 多列下拉框可以搜索其中每列中的數據
演示實例
序——使用軟件及框架版本
- vue 2.6.11
- element-ui 2.15.1
設計思路
之前寫過ant-desing-vue版本的多列下拉框,使用的是select里面使用render
嵌入table表格的方式,顯示多列數據。
由於element-ui組件中沒有render
屬性,所以嘗試使用option中嵌入多個span,給span樣式控制寬度
添加filterable
屬性,提供下拉數據的搜索功能,但是只能搜索所有label中的值,所以找到原生的filter-method
屬性,重寫搜索功能,以實現多列數據的模糊搜索
在提交數據的時候,由於element-ui本身的key
、value
、label
是分離的,所以在在選中option的時候,change方法提交的是當前的value
值
具體代碼過程
1. template模板區域
<template>
<div>
<div class="select-title">甜點:</div>
<el-select
style="width: 600px"
v-model="selectValue"
filterable
placeholder="請選擇"
:filter-method="filterSelectMethod"
@change="change"
>
<el-option
v-for="item in options"
:key="item.select"
:label="item.food"
:value="item.select"
>
<span class="option-span">{{ item.select }}</span>
<span class="option-span-short">{{ item.cookMethod }}</span>
<span class="option-span-long">{{ item.food }}</span>
</el-option>
</el-select>
</div>
</template>
2. js區域
<script>
const selectList = [
{
select: '選項1',
food: '黃金糕黃金糕黃金糕',
cookMethod: '蒸'
},
{
select: '選項2',
food: '雙皮奶',
cookMethod: '炒'
},
{
select: '選項3',
food: '蚵仔煎',
cookMethod: '煎'
},
{
select: '選項4',
food: '龍須面',
cookMethod: '煮'
},
{
select: '選項5',
food: '北京烤鴨',
cookMethod: '烤'
}]
export default {
name: '',
components: {},
watch: {},
data() {
return {
selectValue: "",
options: selectList
}
},
methods: {
change(value) {
console.log(value)
},
filterSelectMethod(key) {
console.log(key)
if (key) {
this.options = selectList.filter(
item =>
item.food.includes(key) ||
item.select.includes(key) ||
item.cookMethod.includes(key)
)
} else {
// console.log(selectList)
this.options = selectList
}
}
},
computed: {},
created() {
},
mounted() {
}
}
</script>
注意事項:
- 定義options數據時,使用
const
定義在外部一個seletList
不可變數據,這樣做為了避免在filterSelectMethod
方法中改變輸入值的時候,影響到opitons
;實際項目中,是大家從后台獲取到的data, - 錯誤例子如下:
// data
options = [
{
select: '選項1',
food: '黃金糕黃金糕黃金糕',
cookMethod: '蒸'
},
{
select: '選項2',
food: '雙皮奶',
cookMethod: '炒'
},
{
select: '選項3',
food: '蚵仔煎',
cookMethod: '煎'
},
{
select: '選項4',
food: '龍須面',
cookMethod: '煮'
},
{
select: '選項5',
food: '北京烤鴨',
cookMethod: '烤'
}]
// method
filterSelectMethod(key) {
console.log(key)
if (key) {
// 如果這樣寫就是不對的,在過濾之后,oitions的值就變為了只有過濾后的值了
this.options = this.options.filter(
item =>
item.food.includes(key) ||
item.select.includes(key) ||
item.cookMethod.includes(key)
)
} else {
//
this.options = this.options
}
}
},
css區域
<style scoped>
.select-title {
margin-bottom: 15px;
/*margin-top: 15px;*/
}
.option-span {
display: inline-block;
padding-right: 5px;
width: 20%;
}
.option-span-short {
display: inline-block;
padding-right: 5px;
width: 20%;
}
.option-span-long {
display: inline-block;
}
</style>
Find me
Gitee: https://gitee.com/heyhaiyon/vue-element-ui.git
微信公眾號:heyhaiyang
掘金:heyhaiyang
博客園:heyhaiyang
頭條號:heyhaiyang