0

I have an very unusual scenario.

<WrapperComponent>
  <InnerComponent propA="Static"></InnerComponent>
</WrapperComponent>

The WrapperComponent should manage all instances of the InnerComponent. However I don't know what will be compiled into the wrapper component.

Usually I would do something like this:

<WrapperComponent>
  <template scoped-slot="{data}">
    <InnerComponent v-for="(propB) in data" prop-b="Static" :prop-b="propB"></InnerComponent>
  </template>
</WrapperComponent>

But I cannot do this for reasons!

I need to be able to create multiple instances of the slot content at runtime. I have created a code sandbox with what I got so far.

https://codesandbox.io/s/stupefied-framework-f3z5g?file=/src/App.vue:697-774

<template>
  <div id="app">
    <WrapperComponent>
      <InnerComponent propA="Static"></InnerComponent>
    </WrapperComponent>
  </div>
</template>

<script>
import Vue from "vue";

const WrapperComponent = Vue.extend({
  name: "WrapperComponent",
  data() {
    return {
      valueMap: ["Child 1", "Child 2"]
    }
  },
  render(h) {
    return h("div", {}, [
      this.valueMap.map(val => {
        console.log(val);
        
        for (const slot of this.$slots.default) {
          // this is a read only slot. I can not change this.
          // However, I want multiple instances of the slot
          // => Inject a scoped-slot
          slot.componentOptions.propsData.propB = val;
        }
        return h("div", {}, [this.$slots.default]);
      })
    ])
  }
});
const InnerComponent = Vue.extend({
  name: "InnerComponent",
  props: {
    // This is a static configuration value.
    propA: String,
    // This is a runtime value. The parent component manages this component
    propB: String
  },
  template: "<div>A: {{propA}} B: {{propB}}</div>"
});
export default {
  name: "App",
  components: {
    WrapperComponent,
    InnerComponent
  }
};
</script>

This works perfectly fine with static information only, but I also have some data that differs per slot instance.

Because VNodes are readonly I cannot modify this.$slot.default.componentOptions.propsData. If I ignore the warning the result will just be the content that was passed to last instance of the slot.

Patrick
  • 29
  • 1
  • 6

1 Answers1

0
 <WrapperComponent>
  <WrapperSubComponent v-for="(propB) in data" key="probB" :prop-b="prop-b"> 
    <InnerComponent propA="Static"></InnerComponent>
  </WrapperSubComponent>
</WrapperComponent>

Works after wrapping the component in another component and only executing the logic once.

Patrick
  • 29
  • 1
  • 6