Step UX-1:通用选择器
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
<template>
|
||||
<el-select
|
||||
:model-value="modelValue"
|
||||
:multiple="multiple"
|
||||
filterable
|
||||
remote
|
||||
clearable
|
||||
:remote-method="onSearch"
|
||||
:loading="loading"
|
||||
:placeholder="placeholder || '请选择用户'"
|
||||
:disabled="disabled"
|
||||
style="width: 100%"
|
||||
@update:model-value="(val) => emit('update:modelValue', val)"
|
||||
>
|
||||
<el-option
|
||||
v-for="u in options"
|
||||
:key="u.id"
|
||||
:label="`${u.username}${u.role ? ' (' + u.role + ')' : ''}`"
|
||||
:value="u.id"
|
||||
/>
|
||||
<template #empty>
|
||||
<div class="empty">{{ loading ? "加载中..." : "无匹配结果" }}</div>
|
||||
</template>
|
||||
</el-select>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ElMessage } from "element-plus";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { fetchUsers } from "../../api/users";
|
||||
|
||||
interface Props {
|
||||
modelValue: string | string[] | null;
|
||||
placeholder?: string;
|
||||
multiple?: boolean;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
const emit = defineEmits(["update:modelValue"]);
|
||||
|
||||
const options = ref<any[]>([]);
|
||||
const loading = ref(false);
|
||||
let timer: number | undefined;
|
||||
const disabled = computed(() => props.disabled ?? false);
|
||||
|
||||
const load = async (keyword = "") => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await fetchUsers({ keyword, limit: 20 });
|
||||
options.value = data.items || data || [];
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || "用户加载失败");
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const onSearch = (keyword: string) => {
|
||||
if (timer) window.clearTimeout(timer);
|
||||
timer = window.setTimeout(() => load(keyword), 300);
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(val) => {
|
||||
// 初次渲染时拉一版数据,确保已选项有 label
|
||||
if (val && options.value.length === 0) {
|
||||
load("");
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.empty {
|
||||
padding: 8px;
|
||||
color: #999;
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user