Same slot content for multiple template slots
Asked Answered
P

3

11

In vuejs, is there a way to set the same content for multiple slots without copy pasting?

So this:

<base-layout>
  <template slot="option">
    <span :class="'flag-icon-'   props.option.toLowerCase()" />{{ countriesByCode[props.option] }}
  </template>

  <template slot="singleLabel">
    <span :class="'flag-icon-'   props.option.toLowerCase()" />{{ countriesByCode[props.option] }}
  </template>
</base-layout>

Could be written that way:

<base-layout>
  <template slot="['option', 'singleLabel']">
    <span :class="'flag-icon-'   props.option.toLowerCase()" />{{ countriesByCode[props.option] }}
  </template>
</base-layout>

Thanks a lot.

Providenciaprovident answered 8/1, 2019 at 11:32 Comment(2)
please indicate that you are using Vuejs, as i see the question is for use it as native htmlVanessa
@ÁlvaroTouzón I've made that more clear in the question (using vue as a tag seemed ok to me).Providenciaprovident
L
11

You could try using v-for for that.

<base-layout>
  <template :slot="slotName" v-for="slotName in ['option', 'singleLabel']">
    <span :class="'flag-icon-'   props.option.toLowerCase()" />{{ countriesByCode[props.option] }}
  </template>
</base-layout>

See working example.

Lampblack answered 8/1, 2019 at 12:46 Comment(1)
I've added slot-scope="props" to the <template/> tag (I've forget this in my question). I hadn't thought about a for loop, thanks for the tip.Providenciaprovident
R
0

The previous answer is no longer valid and currently generates errors.

Here is what currently valid code would look like:

<base-layout>
  <template v-for="slotName in ['option', 'singleLabel']" v-slot:[slotName] :key="slotName">
    <span :class="'flag-icon-'   props.option.toLowerCase()" />{{ countriesByCode[props.option] }}
  </template>
</base-layout>
Ranchero answered 29/2 at 16:8 Comment(0)
I
0

I faced similar issue and went for:

    <template
      v-for="slotName in rowsWithDate"
      :key="slotName"
      #[`item.${slotName}`]="{ item }"
    >
      <p>
        {{
          new Date(item[slotName]).toLocaleDateString(undefined, {
            day: "2-digit",
            month: "long",
            year: "numeric",
          })
        }}
      </p>
    </template>

Where:

import { ref } from "vue";
const rowsWithDate = ref(["birthDate", "createdAt", "updatedAt"]);
Interregnum answered 3/4 at 15:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.