在开发过程中遇到这样一个问题,如何跨组件传递插槽。因为在开发类似树组件的过程中,插槽需要通过外部传递到树的根节点,然后通过根节点依次传递到各个叶子节点。那么如何把根节点的Slot如传递给子组件呢"htmlcode">
<data-tree> <template v-slot:node="data"> <div>{{data.title}} - {{data.text}}</div> </template> </data-tree>
那么如何在组件内传递Slot就是一个问题。
嵌套传递
通过固定级别的组件结构里可以通过直接书写<v-slot ...>来传递对应的Slot元素,来实现一层一层的传递。
<data-tree> <data-tree-item> <template :node="data"> <slot :data="data"> xxx </slot> </template> </data-tree-item> </data-tree>
通过在外层创建slot可以逐层将slot进行传递,但是如果过多的嵌套层次,这样就显得很麻烦。
Render
还有一种方案是通过Render函数来进行显示,可以通过$slots来访问当前组件的slot元素,然后通过Render函数创建新组件时,将slot传递给下一层。
h('data-tree-item',{ scopedSlots: { node: props => this.$slots.node(props) }, })
这样通过Render子元素就可以接受到对应的Slot,也实现了传递。
动态组件
还有一种方式是通过动态组件,也是认为比较推荐的实现方式,不是通过传递Slot,而是通过子节点主动去获取根节点的Slot对象,然后直接在UI中渲染出来。
为此我们需要创建一个组件来渲染对应的Slot对象。
首先需要获取根节点:
const rootComponentName = 'data-tree' /** * 获取父组件 */ const getRootComponent = ( component: ComponentInternalInstance | null ): ComponentInternalInstance | undefined => { if (component && component.type.name === rootComponentName) { return component } if (component && component.parent) { const parent = component.parent return getRootComponent(parent) } }
通过递归我们可以获取到对应的父节点,这样我们就可以把Slot作为Data暴露出来
setup(props) { // 获取根节点 const dataTree = getRootComponent(getCurrentInstance()) const parentSlots = dataTree"htmlcode">components: { TemplateContainer: { functional: true, props: { template: { type: Function }, data: { type: Object } }, render: (props, ctx) => h('div', [props.template(props.data)]) } }好了现在该准备的都准备好了,可以去实现UI的显示了:
<template-container v-if="nodeTemplate" :template="nodeTemplate" :data="node"> </template-container> <template v-else> {{ node.label }} </template>这样我们就实现了类似下面定义Slot的传递,也解决了我们跨组件传递Slot的问题。
<slot :data="node" name="node"> {{ node.label }} </slot>本文使用的是Vue 3的事例,Vue 2也是相同的概念,在Vue 3中除了使用getRootComponent来查询跟节点,也可以使用Provide/Inject来将Slot主动传递给子节点。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 群星.1993-烧得厉害VOL.1好戏好歌唱不停【滚石】【WAV+CUE】
- 魔兽世界wlk阿奴巴拉克怎么打 wlk阿奴巴拉克机制与打法
- 归龙潮阿律的笛子位置在哪 阿律的笛子图文位置一览
- 归龙潮中浦城区福鼠位置在哪 中浦城区福鼠收集位置大全
- NewViennaOctetViennaWindSoloists-TheDeccaRecordings(2024)18CD[24-48][FLAC]-9
- MatteoPasqualini-JohannSebastianBachItalienischesKonzertFranzsischeOuvertureVierDue
- 【雨果唱片】陈百强《梦里人LPCD45》2012[WAV+CUE]
- 《黑神话》纪录片9月20日上线!揭秘关卡为何删减
- 游戏科学估值已和育碧市值相当:后者有两万多名员工
- 黑神话第81周目Boss伤害有多恐怖?起手伤害直接秒
- 群星.2009-原班情歌2CD【SONY】【WAV+CUE】
- 群星.2024-长乐曲电视剧原声带【TME影音】【FLAC分轨】
- 群星.1993-烧得厉害VOL.1好戏好歌唱不停【滚石】【WAV+CUE】
- 那英《幸福的泪 磁性和爆发力完美展现 2CD》[WAV/分轨][600MB]
- 《宝丽金辉煌60年 女人篇3CD》[WAV+CUE][1.5G]