Vue3 Composition Api 检查空槽

Vue3 Composition Api check for empty slot

第一个使用 Vue3 的项目,试图确定命名插槽是否在给定页面上提供了内容。

在我的模板中我有这个:

<div
    :class="{ 'py-20': hasTopContent }"
>
    <slot name="top-content" />
</div>

在我的代码中有以下内容:

setup (_, { slots }) {

    const hasTopContent = computed((slots) => {

        console.log(slots.topContent);

        return slots.topContent && slots.topContent().length;
    });

    return {
        hasTopContent
    }
}

上面的console.log正在返回TypeError: Cannot read properties of undefined (reading 'topContent')。我错过了什么?谢谢!

Michal Levý是对的

var Main = {
    components: {
      'my-component': MyComponent,
    },
    data() {
      return {
      }
    },
    methods: {
    }
};
const app = Vue.createApp(Main);
app.mount("#app")
<html>
<head>
<style>
  .my-component {
    background-color: #fafafa; 
    padding: 5px 20px 20px 20px;
  }
</style>
</head>
<body>
<div id="app">
  <h3>With top slot</h3>
  <my-component class='my-component'>
      <template v-slot:top>
        <h4>Top Slot</h4>
      </template>
  </my-component>
  <h3>Without top slot</h3>
  <my-component class='my-component'>
  </my-component>
  <hr style='padding: 20px 20px 20px 20px;' />
</div>
<script src="//unpkg.com/vue@next"></script>
<script type="text/x-template" id="my-component">
<div
    :class="{ 'py-20': hasTopContent }">
    <slot name="top" />
    hasTopContent: {{hasTopContent}}
</div>
</script>
<script type="text/javascript">    
    var MyComponent = {     
        template: '#my-component',
        setup(_, { slots }) {
        const hasTopContent = Vue.computed(() => {
          return slots.top && slots.top().length > 0;
        });
      return { hasTopContent }
    }
  }
</script>
</body>
</html>