Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

javascript - Bind class to a slot in Vue.js 2

I'm trying to create a reusable component for iterating over items, filtering them, and adding some classes to the slot (if the item is even, odd, first, last etc..)

Here's my reusable component:

<template>
  <ul :class="classes">
    <slot
      v-for="(item, index) in filteredItems"
      :item="item"
      :class="{
        'first': index == 0,
        'odd': !(index % 2),
        'even': index % 2,
        'last': index == (filteredItems.length - 1)
      }"
    >
    </slot>
  </ul>
</template>

<script>
export default {
  props: ['items', 'classes'],
  data() {
    return {
      filteredItems: this.items.filter(item => item.active)
    };
  }
};
</script>

And here's how I use it:

<component-list :classes="'some-class'" :items="category.products">
  <template scope="props">
    <product :product="props.item"></product>
  </template>
<component-list>

Everything works as expected, but it doesn't add classes to the element put inside .

Am I doing anything wrong? Is it even technically possible in Vue.js 2 to do something like this?

Thanks for any help or suggestion!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With vuejs2 styling from slots has been removed as stated here:

Content inserted via named no longer preserves the slot attribute. Use a wrapper element to style them, or for advanced use cases, modify the inserted content programmatically using render functions.

So simplest thing as suggested will be to use a wrapper element as following:

<template>
  <ul :class="classes">
    <slot>
      <div
      v-for="(item, index) in filteredItems"
      :item="item"
      :class="{
        'first': index == 0,
        'odd': !(index % 2),
        'even': index % 2,
        'last': index == (filteredItems.length - 1)
      }"
    >
    </div>
    </slot>
  </ul>
</template>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...