在vue3.0使用tsx,接收不了作用域插槽传递的值

如下代码我有一个child.vue的子组件和parent.tsx的父组件, 但是parent.tsx接收不了作用域插槽的值,在不改变child.vue的前提下,有办法接收值吗?

// parent

import Child from './child.vue'
import { defineComponent, reactive, ref } from 'vue'
export default defineComponent({
  name: '', 
  setup() {
    return () => {
      const slot = {
        item: (text)=> <p>输出值: {text}</p>,
      }
      return (
        <Child>
          {slot}
        </Child>
      )
    }
  },
})
// child.vue
<template>
  <div class="child">
    <div>
      <slot name="item" :text="'hello from child'"></slot>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs } from 'vue'
// import HelloWorld from '@/components/HelloWorld.vue'
export default defineComponent({
  setup() {
  },
})
</script>


<style lang="scss" scoped>
.child{
  background: burlywood;
}
</style>
阅读 6k
2 个回答

将父组件改成这样就行

import { defineComponent, reactive, ref, Slot, Slots } from 'vue'
export default defineComponent({
  name: '',
  setup() {
    return () => {
      const slot: Slots = {
        item: (scope) => [<p>输出值: {scope.text}</p>],
      }
      return <Child>{slot}</Child>
    }
  },
})
export const getSlot = (
  {
    instance,
    ctx,
    props = {}
  }: {
    instance?: ComponentPublicInstance;
    ctx?: SetupContext<EmitsOptions>;
    props?: any;
  },
  name = 'default'
) => {
  const targetSlot = instance?.$slots[name] || ctx?.slots[name];
  return (targetSlot ? targetSlot(instance) : '') || props[name];
};

我一同学写的,通过这个方式获取

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题