index.vue 2.79 KB
<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>