Vue3 组件二次封装

2025-07-02 20:29:57

以 ElInput 为例

ElInputWrapper.vue
App.vue
          <template>
  <div class="my-el-input-wrapper">
    <component :is="h(ElInput, { ...$attrs, ...$props, ref: changeRef }, $slots)"></component>
  </div>
</template>

<script setup lang="ts">
import { h, getCurrentInstance } from 'vue';
import { ElInput, type InputProps, type InputEmits, type InputInstance } from 'element-plus';

defineProps<Partial<InputProps>>()
defineExpose<InputEmits>()
defineSlots<InputInstance['$slots']>()

const vm = getCurrentInstance()

function changeRef(inputInstance: InputInstance) {
  vm.exposed = vm.exposeProxy = inputInstance || {}
}
</script>

        
          <template>
  <h1>{{ msg }}</h1>
  <ElInputWrapper clearable ref="inputRef" v-model="msg">
    <template #append>
      <button @click="inputRef.focus">focus</button>
    </template>
  </ElInputWrapper>
</template>

<script setup lang="ts">
import { ref, useTemplateRef } from 'vue';
import ElInputWrapper from './ElInputWrapper.vue';

const msg = ref('Hello World!')
const inputRef = useTemplateRef('inputRef')
</script>

        
© 2021-2025 sunshj's Blog