Detlef
Detlef

Reputation: 8592

Render named scopedSlot programmatically

I want to move the following template into the render function of my component, but I don't understand how.

This is my template:

<template>
  <div>
      <slot name="item" v-for="item in filteredItems" :item="item">
        {{ item.title }}
      </slot>
  </div>
</template>

This is my component:

export default {
  props: {
    items: {
      type: Array,
      required: true,
    },
    search: {
      type: String,
      default: ""
    }
  },
  methods: {
    filterByTitle(item) {
      if (!("title" in item)) { return false; }
      return item.title.includes(this.search);
    }
  },
  computed: {
    filteredItems() {
      if (this.search.length === "") {
        return this.items;
      }
      return this.items.filter(this.filterByTitle);
    }
  },
  render: function(h) {
    // How can I transform the template so that it finds its place here? 
    return h('div', ...);
  }
};

I thank you in advance.

Upvotes: 0

Views: 929

Answers (1)

User 28
User 28

Reputation: 5158

To render scoped slots you can use $scopedSlots. See more here.

Example Code:

...
  render(h) {
    return h(
      'div',
      this.filteredItems.map(item => {
        let slot = this.$scopedSlots[item.title]
        return slot ? slot(item) : item.title
      })
    )
  }
...

JSFiddle

Upvotes: 1

Related Questions