如何设计一个组件
需求分析
布局
- 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"> <