二次封装 input 自定义的内容,二次封装的一些小技巧

父组件:

<template>
  <div class="w-[500px]">
    <h1 class="mb-20">父组件</h1>
    <MyInput ref="inputRef" v-model="msg">
      <template #append>
        <div>append</div>
      </template>
    </MyInput>
  </div>
</template>
<script setup lang="ts">
  import MyInput from '@/components/MyInput.vue'
  import { ref } from 'vue'
  const inputRef=ref()
  const msg=ref("Hello World")
  setTimeout(()=>{
    console.log("inputRef.value=>",inputRef.value)
    inputRef.value.clear()
  },1000)
</script>
<style scoped>

</style>

MyInput子组件

<template>
  <div>
    <div>二次封装 input 自定义的内容</div>
    <component :is="h(ElInput, { ...$attrs, ...props, ref: changRef }, $slots)"></component>
  </div>
</template>

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

const props = defineProps<Partial<InputProps>>()
const vm = getCurrentInstance()

function changRef(inputInstance: any) { 
  if (vm) {
    vm.exposed = inputInstance || {}
    vm.exposeProxy = inputInstance || {}
  }
}

/**
 * 问题:
 * 1. 如何让 props 穿透到子组件?
 * 2. 如何让插槽内容穿透到子组件?
 * 3. 如何将组件的方法暴露给父组件使用?
 */
</script>

<style scoped></style>


复制内容

留言讨论


评论


乖,登录后才可以留言! 登录

广而告之

Copyright © 2020-2023 春藤技术,春藤建站 All Rights Reserved
备案号:豫ICP备20020705号 公网安备 51LA统计