vue3 包裹组件 透传props和slots

82 阅读1分钟

如下

<script setup lang="ts">
import { defineOptions, getCurrentInstance, useSlots, ref } from 'vue'

const slots = useSlots()

defineOptions({
  name: 'MySelect'
})
// 这个实在没找到类型是啥 就整了个any
const defaultProps: any = {
  variant: 'outlined',
  label: 'Select',
  hideDetails: 'auto',
  density: 'compact'
}
const { attrs } = getCurrentInstance()
const tempAttrs = { ...defaultProps, ...attrs }
const VSelectRef = ref(null)

defineExpose({
  VSelectRef // <script setup>的组件里的属性默认是关闭的,需通过defineExpose暴露出去才能被调用
})
</script>

<template>
  <v-select ref="selectRef" v-bind="tempAttrs">
    <template v-for="(item, key, i) in slots" :key="i" v-slot:[key]="scoped">
      <slot :name="key" v-bind="scoped"></slot>
    </template>
  </v-select>
</template>

<style scoped></style>