Vue.js 3 中的插槽继承

inc*_*nez 2 javascript vue.js vue-component vuejs3

我试图了解如何/是否可以在 Vue.js v3 中定义某种插槽继承。我有一个Container定义 2 个插槽的类:titleitems。我Container在我的班级中进行扩展,并在那里Grid定义了插槽。items当我去使用我的Grid课程时,我想定义插槽title小提琴供参考。

容器.vue

<template>
  <div>
    <header v-if="showTitle">
      <slot name="title" />
    </header>

    <main v-if="showItems">
      <slot name="items" />
    </main>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "MyContainer",
  computed: {
    showTitle() {
      return !!this.$slots.title;
    },
    showItems() {
      return !!this.$slots.items;
    },
  },
});
</script>
Run Code Online (Sandbox Code Playgroud)

Grid.vue

<template>
  <MyContainer>
    <template #items>
      <span>Here are my items</span>
    </template>
  </MyContainer>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import MyContainer from "@/components/base/Container";

export default defineComponent({
  name: "MyGrid",
  extends: MyContainer,
  components: { MyContainer },
});
</script>
Run Code Online (Sandbox Code Playgroud)

应用程序.vue

<template>
  <div id="app">
    <MyGrid>
      <!-- How can I pass this along to MyGrid's base class? -->
      <template #title>
        <span>This is my title!</span>
      </template>
    </MyGrid>
  </div>
</template>

<script>
import MyGrid from "@/components/base/Grid";

export default {
  name: "App",
  components: {
    MyGrid,
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

问题在于App.vue我在模板中添加了注释——我想传递在那里定义插槽的信息。这可能吗?

inc*_*nez 5

根据this,我必须定义一个模板,该模板本质上传递实例上定义的任何插槽。所以在我的Grid.vue课堂上,我会添加以下代码:

<template>
  <MyContainer>
    <template #items>
      <span>Here are my items</span>
    </template>
    <!-- Added this template -->
    <template v-for="(_, name) in $slots" v-slot:[name]="slotData">
      <slot :name="name" v-bind="slotData" />
    </template>
  </MyContainer>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import MyContainer from "@/components/base/Container";

export default defineComponent({
  name: "MyGrid",
  extends: MyContainer,
  components: { MyContainer },
});
</script>
Run Code Online (Sandbox Code Playgroud)