功能描述
(1)某个变量的值通过下拉选择得出;
(2)下拉数据量大;
(3)只能通过分页获取的下拉数据;
(4)可根据搜索内容动态显示下拉数据。
能同时满足这几个项目要求,select组件的基本能实现,为在项目中更好的复用这个功能和使用时更简洁,接下来就封装成新的组件datat-select。
Props
参数 | 描述 | 类型 | 默认值 |
---|---|---|---|
v-model | 选中值 | string | - |
width | 选择框的宽度 | string | “100%” |
fieldNames | 自定义 options 中 label value 的字段 | object | { label: ‘label’, value: ‘value’} |
getList | 请求后端list接口的方法 | function(params) | - |
searchName | 需要搜索的字段名 | string | - |
placeholder | 输入提示语 | sting | - |
pageSize | 如果数据是分页加载,那么默认一次加载多少条 | number | 20 |
代码实现
<template>
<Select
v-model:value="currentValue"
show-search
:placeholder="placeholder || '搜索名称'"
:style="{ width }"
:options="options"
allowClear
:filter-option="filterOption"
:fieldNames="fieldNames"
@search="searchChange"
/>
</template>
<script setup>
import { ref, defineProps, defineEmits, watch, onMounted, computed } from "vue";
import { Select } from "ant-design-vue";
import useApi from "@/utils/hooks/use-api";
import { useDebounceFn } from "@vueuse/core";
/**
* 大数据且分页查询时用到的选择框组件,根据搜索条件查询后端数据
*/
const props = defineProps({
width: {
type: String,
default: "100%"
},
modelValue: String,
fieldNames: Object,
getList: Function, //请求后端list接口的方法
searchName: String, //需要搜索的字段名
placeholder: String,
pageSize: { type: Number, default: 20 }
});
const emits = defineEmits(["update:modelValue"]);
const currentValue = computed({
get: () => props.modelValue,
set: (v) => emits("update:modelValue", v)
});
const options = ref([]);
const filterOption = () => true;
const { result: listResult, fetchResource: fetchList } = useApi(props.getList);
const getOptionList = async (params = {}) => {
await fetchList({
...params,
pageNum: 1,
pageSize: props.pageSize
});
options.value = listResult.value?.data?.datas || [];
};
watch(currentValue, (newValue) => {
!newValue && getOptionList();
});
const searchChange = useDebounceFn((value) => {
getOptionList({
[props.searchName || props.fieldNames?.label || "name"]: value
});
}, 300);
onMounted(async () => {
getOptionList();
});
</script>