我正在构建一个小型库,它允许从其他组件中修改应用程序布局的一部分。
基本思想是拥有一个主导航组件:
<template>
<div class='main-navigation>
<div class='logo'><img...>
<div class='actions'>
<Container name='extra-actions' />
<a href="some-action">Action</a>
</div>
</template>组件然后可以使用以下内容注册其他内容:
<template>
<div class='home-page'>
<ContentFor container="extra-actions">
<a href='some-home-specific-action'>Do sth extra</a>
</ContentFor>
...rest of the page
</div>
</template>我通过使用定制插件和服务对象将插槽注册(和更新)为ContentFor中定义的VNode,并将其呈现在容器中,从而成功地实现了上述功能。我现在想通过允许用户为每个给定的内容添加自定义布局来增强它,例如:
<ul class='actions'>
<Container name='extra-actions'>
<li><slot></slot></li>
</Container>
</ul>这将很好地将视图组件从导航结构中分离出来。我尝试过以下几种方法:
render (h) {
return h(Fragment, Object.values(this.contents).map((content) => {
if (this.$scopedSlots.default) {
return this.$scopedSlots.default({
slots: { default: content.slot } # this does nothing!
})
} else {
# This works as expected
return content.slot
}
}))
},当没有自定义模板时,上面的方法工作得很好。当存在自定义模板时,它会呈现该模板,但不会将内容传递到模板的插槽,从而导致:
<ul class='actions'>
<li></li> # instead of <li><a href='some-home-specific-action'>Do sth extra</a></li>
</ul>是否有任何特定的方法可以将作用域传递到其他作用域?
发布于 2019-11-18 19:42:16
因此,在反复使用它之后,我了解到这不可能用插槽来解决我的模板问题。当我这样做的时候
# layout/Navigation.vue
<ul>
<Container name='main-nav-actions>
<li><slot/></li>
</Container>
</ul>在导航组件的上下文中解析</slot> -这意味着它是一个静态的VNodes数组。因此,插槽不能有自己的动态嵌套插槽。
取而代之的是,我必须编写一个功能组件来负责呈现VNodes:
export {
name: 'RenderContent',
functional: true,
render (h, { props }) { return props.content }
}公开后,我现在可以使用scopedSlot构建我的模板:
<Container name='main-nav-actions vue-slot="{ content }">
<li><RenderContent :content="content"></li>
</Container>这不是最漂亮的解决方案,但它似乎有效,允许通过ContentFor传递可选选项,这非常好。
https://stackoverflow.com/questions/58889743
复制相似问题