index.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { Button, Icon, Search } from 'vant';
  2. import { PropType, defineComponent, reactive, ref, watch } from 'vue';
  3. import styles from './index.module.less';
  4. import iconSearch from './images/icon_search.png';
  5. export default defineComponent({
  6. name: 'm-search',
  7. props: {
  8. modelValue: {
  9. type: String,
  10. default: ''
  11. },
  12. shape: {
  13. type: String as PropType<'round' | 'square'>,
  14. default: 'round'
  15. },
  16. disabled: {
  17. type: Boolean,
  18. default: false
  19. },
  20. clearable: {
  21. type: Boolean,
  22. default: true
  23. },
  24. autofocus: {
  25. // ios系统不支持
  26. type: Boolean,
  27. default: false
  28. },
  29. placeholder: {
  30. type: String,
  31. default: '请输入搜索关键词'
  32. },
  33. background: {
  34. type: String,
  35. default: '#fff'
  36. },
  37. searchIcon: {
  38. type: String,
  39. default: iconSearch
  40. },
  41. inputBackground: {
  42. type: String,
  43. default: '#f8f9fc'
  44. }
  45. },
  46. emits: ['search', 'focus', 'blur'],
  47. setup(props, { slots, emit, expose }) {
  48. const forms = reactive({
  49. search: props.modelValue || '',
  50. });
  51. const searchRef = ref()
  52. watch(
  53. () => props.modelValue,
  54. () => {
  55. forms.search = props.modelValue;
  56. }
  57. );
  58. const searchBlur = () => {
  59. searchRef.value?.blur()
  60. }
  61. expose({
  62. searchBlur
  63. })
  64. return () => (
  65. <Search
  66. class={[styles['m-search'], styles[props.inputBackground]]}
  67. style={{"--van-search-content-background": props.inputBackground}}
  68. ref={searchRef}
  69. shape={props.shape}
  70. background={props.background}
  71. placeholder={props.placeholder}
  72. disabled={props.disabled}
  73. autofocus={props.autofocus}
  74. autocomplete="off"
  75. clearable={props.clearable}
  76. v-model={forms.search}
  77. clearTrigger="always"
  78. onClear={() => {
  79. console.log('clear');
  80. forms.search = '';
  81. emit('search', forms.search);
  82. }}
  83. onFocus={() => emit('focus')}
  84. onBlur={() => emit('blur', forms.search)}
  85. onSearch={() => emit('search', forms.search)}>
  86. {{
  87. left: () => slots.left && slots.left(),
  88. 'left-icon': () => (
  89. <Icon name={props.searchIcon} class={styles.leftIcon} />
  90. ),
  91. 'right-icon': () => (
  92. <Button
  93. disabled={props.disabled}
  94. class={styles.searchBtn}
  95. round
  96. type="primary"
  97. size="mini"
  98. onClick={() => emit('search', forms.search)}>
  99. 搜索
  100. </Button>
  101. )
  102. }}
  103. </Search>
  104. );
  105. }
  106. });