如何在运行时将插槽包装到作用域插槽中



我有一个非常不寻常的场景。

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

WrapperComponent应该管理InnerComponent的所有实例。然而,我不知道什么会被编译到包装器组件中。

通常我会这样做:

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

但我不能这么做是有原因的

我需要能够在运行时创建插槽内容的多个实例。我已经创建了一个代码沙箱与我迄今为止所得到的。

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>

这只适用于静态信息,但我也有一些不同插槽实例的数据。

因为VNode是只读的,所以我不能修改它$slot.default.componentOptions.propsData。如果我忽略警告,结果将只是传递给插槽最后一个实例的内容。

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

在将组件包装到另一个组件中并只执行一次逻辑后工作。

最新更新