簡體   English   中英

Vue.js 3 - 將組件插入插槽

[英]Vue.js 3 - inserting component into slot

我想要達到的目標

我正在嘗試將Component傳遞到slot

問題/信息

如何將Component傳遞到slot中以便渲染? 只要我通過字符串/普通 html,這工作正常。

附加問題

如果這是不可能的 - 那么我如何將組件傳遞給具有如下結構的其他組件?

家長

模板代碼

<template>
  <card-with-title card-title="Title">
    <template #card-body>
      <row-fontawesome-icon-with-text v-for="mailDto in lastProcessedEmails"/>
    </template>
  </card-with-title>
</template>

腳本代碼 - 重要部分

<script>
import SymfonyRoutes                     from '../../../../../core/symfony/SymfonyRoutes';
import GetLastProcessedEmailsResponseDto from '../../../../../core/dto/api/internal/GetLastProcessedEmailsResponseDto';
import MailDto                           from '../../../../../core/dto/modules/mailing/MailDto';

import CardWithTitleComponent              from '../../../../base-layout/components/cards/card-with-title';
import RowFontawesomeIconWithTextComponent from '../../../../other/row-fontawesome-icon-with-text';

export default {
  components: {
    'card-with-title'                : CardWithTitleComponent,
    'row-fontawesome-icon-with-text' : RowFontawesomeIconWithTextComponent,
  },
<...>

孩子

<!-- Template -->
<template>
  <div class="col-12 col-lg-4 mb-4">
    <div class="card border-light shadow-sm">
      <div class="card-header border-bottom border-light">
        <h2 class="h5 mb-0">{{ cardTitle }}</h2>
      </div>
      <div class="card-body">
        <slot name="card-body"></slot>
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<!-- Script -->
<script>
export default {
  props: [
      "cardBody",
      "cardStyle",
      "cardTitle"
  ],
}
</script>

我對這個問題進行了研究,我在文檔中看到了命名插槽的工作方式,但沒有帖子/博客條目回答/解決我的問題。

檢查資源的示例:

我找到了解決方案……這非常……可怕。 Vue不會檢查數組是否為空,在v-for它會嘗試循環然后拋出錯誤。

就個人而言,來自其他語言/框架 - 這不應該發生。

但是,這是解決方案:

<!-- Template -->
<template>

  <card-with-title card-title="Title">
    <template #card-body>
      <div v-if="[lastProcessedEmails.length]">

        <row-fontawesome-icon-with-text v-for="mailDto in lastProcessedEmails">
          <template #icon>
            <i class="font-weight-bold">
              <i v-if="mailDto.status === mailStatusSent"         :class="fontawesomeIconClassesSent"></i>
              <i v-else-if="mailDto.status === mailStatusPending" :class="fontawesomeIconClassesPending"></i>
              <i v-else                                             :class="fontawesomeIconClassesError"></i>
            </i>
          </template>

          <template #title>
            {{ mailDto.subject }}
          </template>

          <template #title-context>
            {{ mailDto.created }}
          </template>
        </row-fontawesome-icon-with-text>

      </div>
    </template>
  </card-with-title>

</template>

整個問題是:

  data(){
    return {
      lastProcessedEmails: [],
    }
  },

lastProcessedEmails通過 Axios 調用更新。

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM