3 回答
TA贡献1801条经验 获得超8个赞
不同之处在于,在您的 中reduce
,您创建的函数为
() => { createElement( 'div', 'hello world') }
在您的硬编码版本中(也在forEach
@Boussadjra的答案中的循环中),它们被创建为
() => createElement('div', 'hello world')
这实际上是return
创建的元素。这与使用无关reduce
,这很好。
const ReplicatorComponent = {
template: `<div>
<h1>replicator-component</h1>
<slot name='element_1'></slot>
<slot name='element_2'></slot>
<slot name='element_3'></slot>
</div>`
};
const records = [
{ "index": 1 },
{ "index": 2 },
{ "index": 3 },
];
Vue.component('my-component', {
render: function(createElement) {
return createElement(ReplicatorComponent, {
attrs: {
elements: records.length
},
scopedSlots: records.reduce((a,x) => ({
...a,
['element_' + x.index]: () =>
createElement( 'div', 'hello world')
}), {})
});
},
});
new Vue({
el: '#app',
data: () => ({})
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<div id="app">
<my-component></my-component>
</div>
TA贡献1111条经验 获得超0个赞
该reduce方法不起作用,因为它之前缺少返回createElement('div', 'hello world'):
完整示例
const ReplicatorComponent = {
template: `
<div>
<h1>replicator-component</h1>
<slot name='element_1'></slot>
<slot name='element_2'></slot>
<slot name='element_3'></slot>
</div>
`
}
const records = [{
"index": 1,
},
{
"index": 2,
},
{
"index": 3,
}
]
Vue.component('my-component', {
render: function(createElement) {
let slotContent = records.reduce((a, x) => ({ ...a,
['element_' + x.index]:
() => {
return createElement('div', 'hello world')
}
}), {})
return createElement(ReplicatorComponent, {
attrs: {
elements: records.length
},
scopedSlots: slotContent
});
},
})
var app = new Vue({
el: '#app',
data: () => ({})
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<div id="app">
test
<my-component></my-component>
</div>
TA贡献1847条经验 获得超7个赞
我认为作用域插槽应该是props根据 Vue.js 文档作为参数的函数
export default {
render(createElement) {
// ...
// some other stuff
// ...
// Scoped slots in the form of
// { name: props => VNode | Array<VNode> }
scopedSlots: {
default: props => createElement('span', props.text)
},
}
}
所以也许你应该尝试一下
v-slot你也可以使用 vue 的新统一系统完成同样的事情
<!-- page component -->
<template>
<some-component>
<template v-for="slot in scopedSlots" v-slot:[slot]="props">
hello {{props}}
</template>
</some-component>
</template>
<!-- some-component.vue -->
<template>
<div>
<slot v-for="slot in Object.keys($slots)" :name="slot"></slot>
</div>
</template>
添加回答
举报