【转】vue3二次封装element组件多层透传属性 & 插槽

需求:二次封装element组件,需要支持原属性和插槽,这里分别说一下SFC和TSX的透传方式

透传属性 attrs

SFC: v-bind="$attrs" 和 useAttrs

// index.vue
<el-input v-bind="$attrs" />
// index.vue
<script setup lang="ts">
import { useAttrs } from "vue";
const attrs = useAttrs()
</script>
<template>
  <el-input v-bind="attrs" />
</template>

TSX: {...attrs}

*setup(props,context)函数中上下文参数context,包含attrs、emit、slots
// index.tsx
import { defineComponent } from "vue";
export default defineComponent({
    setup(props, {attrs}) {
        return () => (
          <el-input {....attrs}></el-input>
        );
    }
})

透传属性 slots

SFC: useSlots

// index.vue
<script setup lang="ts">
import { useSlots } from "vue";
const slots = useSlots()
</script>
<template>
  <el-input v-bind="$attrs">
    <!-- 遍历父组件传入的 solts 透传给子组件 -->
    <template v-for="(item, key, i) in slots" :key="i" v-slot:[key]>
      <slot :name="key"></slot>
    </template>
  </el-input>
</template>

TSX: v-solts={slots}

// index.tsx
import { defineComponent } from "vue";
export default defineComponent({
    setup(props, {attrs、emit、slots}) {
        return () => (
          <el-input v-slots={slots}></el-input>
        );
    }
})

作者:柒号
链接:https://juejin.cn/post/7188054070152822845
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

我的透传方式

<template>
  <AButton @click="clickHandle" v-bind="otherProps">
    <template v-for="(item, key, i) in slots" :key="i" v-slot:[key]>
      <slot :name="key"></slot>
    </template>
  </AButton>
</template>

<script setup lang="ts">
import type { ButtonProps } from 'ant-design-vue'

const props = withDefaults(defineProps<ButtonProps & {
  /**
   * 鼠标点击延迟时间,默认500
   */
  delayTime?: number
}>(), {
  delayTime: 500,
})

const otherProps = computed(() => Object.assign({}, props, { onClick: undefined }))
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容