uniapp自己封装一个select组件
我在uniapp找了很久的select组件,发现可选的uni-combox
组件和uni-data-select
组件都不符合我的需求,uni-combox
不能使用对象数组,而uni-data-select不能输入搜索。所以我自己封装了一个小组件(这里我项目用的vue3+ts+vite+uniapp
),大家可以拿在这里插入代码片去直接用或者更加完善,话不多说,直接上代码:
<template>
<view class="select">
<uni-easyinput
v-model="selectValue"
:placeholder="placeholder"
@blur="blur"
@change="change"
@focus="focus"
@input="input"
>
</uni-easyinput>
<scroll-view scroll-y class="item-box" v-show="isShow">
<view v-if="selectOptionList.length === 0" class="item">暂无数据</view>
<view v-for="item,index in selectOptionList" class="item" hover-class="item-hover" @click="changeValue(item)">{{ item[labelKey] }}</view>
</scroll-view>
</view>
</template>
<script lang="ts" setup>
import {isShallow, ref} from 'vue'
import { onShow } from '@dcloudio/uni-app';
const selectValue = ref('')//选择的值
const isShow = ref(false)//是否显示
const props = defineProps({
labelKey:{type:String,default:'label'},//自定义label值
valueKey:{type:String,default:'value'},//自定义value值
optionList:{type:Array,default:[]},//可选值数组
placeholder:{type:String,default:'请选择'}//提示语
})
const Emit = defineEmits(["selectItem"])
const selectOptionList = ref([])
onShow(()=>{
selectOptionList.value = props.optionList
})
const focus = ()=>{
isShow.value = true
}
const blur = ()=>{
setTimeout(() => {
isShow.value = false
});
}
const change = ()=>{
}
const changeValue = (item)=>{
selectValue.value = item[props.labelKey]
Emit("selectItem",item)
}
const input = (e)=>{
if(e){
selectOptionList.value = props.optionList.filter(item=> item[props.labelKey].indexOf(e) > -1);
return
}
selectOptionList.value = props.optionList
}
</script>
<style lang="scss" scoped>
.select{
position: relative;
width: 100%;
height: 40px;
.item-box{
position: absolute;
width: 100%;
display:flex;
flex-direction:column;
max-height: 150px;
border-radius:4px;
box-shadow:0 4px 10px 0 #D5D5D5;
z-index:999;
background:#ffffff;
.item{
font-size:14px;
height:36px;
display:flex;
align-items:center;
text-indent: 10px;
}
.item-hover{
background:#F6F8FB;
}
}
}
</style>
使用方式:(外层的view需要设置宽度,否则就是当前盒子的100%宽度),如果你的对象属性值不是value和label的话可以根据你的需求进行更改。
<view class="task">
<Select @selectItem="selectItem" placeholder="请选择考核任务" :optionList="taskList" valueKey="value" labelKey="label"/>
</view>
const taskList = ref([{value:1,label:'哈哈哈'},{value:2,label:'嘿嘿嘿'}])
const selectItem = (data)=>{
console.log(data);
}
一个小组件还需要完善,我先发篇博客记录一下。