Search.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <script setup>
  2. import { computed, ref } from "vue";
  3. const props=defineProps({
  4. defaultVal:{
  5. type:String,
  6. default:''
  7. },
  8. placeholder:{
  9. type:String,
  10. default:'请输入关键词'
  11. },
  12. disabled:{//是否禁用
  13. type:Boolean,
  14. default:false
  15. },
  16. autoFocus:{
  17. type:Boolean,
  18. default:false
  19. }
  20. })
  21. const emit = defineEmits(["search",'clean','blur'])
  22. let searchData = ref(props.defaultVal||"");
  23. let isFocus=ref(false)
  24. let showClean = computed(() => {
  25. return searchData.value.length > 0 ? true : false;
  26. });
  27. const handleFocus = () => {
  28. //聚焦到input框上,样式改变
  29. isFocus.value=true
  30. };
  31. const handleBlur = () => {
  32. isFocus.value=false
  33. };
  34. const handleClean = () => {
  35. searchData.value = "";
  36. emit('clean')
  37. };
  38. const handleSearch = ()=>{
  39. if(!searchData.value.length) return
  40. emit('search',searchData.value)
  41. }
  42. </script>
  43. <template>
  44. <div :class="['search-wrap',(isFocus||searchData)&&'focus']">
  45. <span v-show="!isFocus&&!searchData"></span>
  46. <input
  47. type="text"
  48. :placeholder="props.placeholder"
  49. :autofocus="props.autoFocus"
  50. v-model="searchData"
  51. @blur="handleBlur"
  52. @focus="handleFocus"
  53. @keyup.enter="handleSearch"
  54. :disabled="props.disabled"
  55. />
  56. <span class="clean" v-show="showClean" @click="handleClean"></span>
  57. </div>
  58. </template>
  59. <style lang="scss" scoped>
  60. .search-wrap {
  61. display: flex;
  62. align-items: center;
  63. padding: 10px 20px;
  64. // position: absolute;
  65. // right: 160px;
  66. width: 300px;
  67. height: 40px;
  68. // top: 50%;
  69. // margin-top: -20px;
  70. border-radius: 20px;
  71. background-color: #ebebeb;
  72. border: 1px solid #ebebeb;
  73. transition: 0.3s;
  74. &.focus {
  75. background: #ffffff;
  76. border: 1px solid #f3a52f;
  77. }
  78. span {
  79. display: inline-block;
  80. width: 14px;
  81. height: 14px;
  82. background: no-repeat center/cover url("../assets/icon-search.png");
  83. margin-right: 6px;
  84. &.clean {
  85. width: 20px;
  86. height: 20px;
  87. margin-right: 0;
  88. cursor: pointer;
  89. background: no-repeat center/cover url("../assets/icon-close.png");
  90. }
  91. }
  92. input {
  93. flex: 1;
  94. background: none;
  95. outline: none;
  96. border: none;
  97. }
  98. }
  99. </style>