【问题标题】:Vue3 Composition Api check for empty slotVue3 Composition Api 检查空槽
【发布时间】:2021-11-15 19:09:07
【问题描述】:

第一个使用 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')。我错过了什么?谢谢!

【问题讨论】:

  • 通过执行computed((slots) =&gt;{ .... }),您正在创建一个具有slots 参数的函数(始终为undefined)。所以computed 中的代码使用这个参数而不是父作用域中的slots 变量。只需改用computed(() =&gt; {....}...

标签: vuejs3 slots


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 2022-01-25
    • 2021-06-08
    • 1970-01-01
    • 2021-04-03
    • 2022-01-23
    • 2021-11-30
    • 1970-01-01
    • 2022-06-29
    相关资源
    最近更新 更多