ele-h5项目使用vue3+vite+vant4开发:第二节、search 搜索框组件开发

如何设计一个组件

 需求分析

 布局

  • content
    • left-icon
    • body
    • input-control
    • right-icon
  • action

功能

使用 defineEmits 定义组件的事件

在组件的script setup 里如何定义事件

  • 使用defineEmits()定义
  • 先声明事件接口
  • <script setup lang="ts">
    interface IProps {
      showAction?: boolean
      background?: string
      placeholder?: string
      shape?: string
      modelValue?: string | number
    }
    
    const props = defineProps<IProps>()
    
    // 声明事件接口
    interface IEmits {
      (e: 'search', v?: string | number): void
      (e: 'cancel'): void
      (e: 'clear'): void
      (e: 'update:modelValue', v?: string | number): void
    }
    
    // 定义事件变量
    const emits = defineEmits<IEmits>()
    
    const onKeyPress = (e: KeyboardEvent) => {
      const ENTER_CODE = 13
      if (ENTER_CODE === e.keyCode) {
        e.preventDefault()
    //使用定义事件里声明事件接口中的某个事件
        emits('search', props.modelValue)
      }
    }
    
    const onClear = () => {
    //使用定义事件里声明事件接口中的某个事件
      emits('clear')
    //使用定义事件里声明事件接口中的某个事件
      emits('update:modelValue', '')
    }
    </script>
    
    <template>
      <div class="op-search" :class="{ 'op-search--show-action': showAction }" :style="{ background }">
        <div class="op-search__content" :class="shape ? `op-search__content--${shape}` : ''">
          <div class="op-cell op-search__field">
            <div class="op-field__left-icon">
              <VanIcon name="search" />
            </div>
            <div class="op-cell__value">
              <div class="op-field__body">
                <input
                  type="search"
                  class="op-field__control"
                  :value="modelValue"
                  :placeholder="placeholder"
                  @keypress="onKeyPress"
    
                //使用定义事件里声明事件接口中的某个事件, 以及传递input输入框里的值
                  @input="(e) => emits('update:modelValue', (e.target as HTMLInputElement).value)"
                />
                <div v-if="$slots['right-icon']" class="op-field__right-icon">
                  <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值