<el-autocomplete
v-model="queryParams.title"
:fetch-suggestions="querySearch"
placeholder="请选择类别"
@select="handleSelect"
clearable
style="width: 150px"
>
<template #default="{ item }">
<div>
<div v-if="item.label.length <= 10">
<span>{{ item.label }}</span>
</div>
<div v-else style="overflow: hidden; text-overflow: ellipsis">
<el-tooltip class="item" effect="light" :content="item.label" placement="right">
<span>{{ item.label }}</span>
</el-tooltip>
</div>
</div>
</template>
</el-autocomplete>
在 Element Plus
的 <el-autocomplete>
组件中,#default
插槽用于自定义下拉选项的渲染内容。item
是传递给插槽的当前选项数据,其结构取决于你在 fetch-suggestions
方法中返回的数据结构。
1. item
的结构
item
的结构是由你在 fetch-suggestions
方法中返回的数组元素决定的。通常,item
是一个对象,包含以下常用字段:
-
label
:显示在下拉列表中的文本。 -
value
:选中该项后绑定到v-model
的值。 -
其他自定义字段:根据业务需求,可以包含更多字段(如
id
、description
等)。
2. #default
插槽的作用
#default
插槽用于自定义每个下拉选项的渲染内容。通过 { item }
可以访问当前选项的数据。
3. fetch-suggestions
方法
fetch-suggestions
是一个异步方法,用于根据输入值获取下拉选项。它需要返回一个数组,数组中的每个元素会成为 item
。
4. item
的常见使用场景
-
显示文本:
item.label
用于显示在下拉列表中。 -
绑定值:
item.value
用于选中后绑定到v-model
。 -
自定义渲染:通过
#default
插槽,可以自定义选项的样式和内容(如添加图标、省略号等)。