index.vue
2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<script setup lang="ts">
import { computed } from 'vue';
import { ElInput } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { useDebounceFn } from '@vueuse/core';
import type { VSearchBoxEmits, VSearchBoxProps } from '../../types';
/**
* VSearchBox - 搜索框组件
* 基于 Element Plus ElInput 的二次封装
* 提供防抖搜索、清空、回车搜索等功能
*/
defineOptions({
name: 'VSearchBox',
});
const props = withDefaults(defineProps<VSearchBoxProps>(), {
modelValue: '',
placeholder: '请输入搜索内容',
clearable: true,
debounce: 300,
showSearchButton: true,
searchButtonText: '搜索',
size: 'default',
disabled: false,
prefixIcon: undefined,
});
const emit = defineEmits<VSearchBoxEmits>();
// 计算输入框的值
const inputValue = computed({
get: () => props.modelValue,
set: (value: string) => {
emit('update:modelValue', value);
emit('input', value);
// 触发防抖搜索
if (props.debounce > 0) {
debouncedSearch(value);
}
},
});
// 处理搜索
const handleSearch = (value?: string) => {
const searchValue = value ?? inputValue.value;
emit('search', searchValue);
};
// 防抖搜索
const debouncedSearch = useDebounceFn((value: string) => {
emit('search', value);
}, props.debounce);
// 处理清空
const handleClear = () => {
emit('clear');
emit('search', '');
};
// 处理回车
const handleKeyEnter = () => {
handleSearch();
};
</script>
<template>
<div class="v-search-box">
<ElInput
v-model="inputValue"
:placeholder="placeholder"
:clearable="clearable"
:size="size"
:maxlength="maxlength"
:disabled="disabled"
:prefix-icon="prefixIcon || Search"
class="v-search-box__input"
@clear="handleClear"
@keyup.enter="handleKeyEnter"
>
<template v-if="showSearchButton" #append>
<el-button
:icon="Search"
:size="size"
:disabled="disabled"
@click="() => handleSearch()"
>
{{ searchButtonText }}
</el-button>
</template>
<!-- 透传所有插槽 -->
<template v-for="(_, name) in $slots" #[name]="slotProps">
<slot :name="name" v-bind="slotProps || {}" />
</template>
</ElInput>
</div>
</template>
<style scoped>
.v-search-box {
display: inline-block;
width: 100%;
}
.v-search-box__input {
width: 100%;
}
/* 搜索按钮样式优化 */
:deep(.el-input-group__append) {
background-color: var(--el-color-primary);
color: #fff;
border-color: var(--el-color-primary);
padding: 0;
}
:deep(.el-input-group__append .el-button) {
background-color: transparent;
color: inherit;
border: none;
margin: 0;
}
:deep(.el-input-group__append .el-button:hover) {
background-color: rgba(255, 255, 255, 0.1);
}
</style>