在开发过程中遇到这样一个问题,如何跨组件传递插槽。因为在开发类似树组件的过程中,插槽需要通过外部传递到树的根节点,然后通过根节点依次传递到各个叶子节点。那么如何把根节点的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主动传递给子节点。
风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][502.8MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量编号[WAV+CUE]
- 曼丽2020《女人三十风继续吹》HQCD[WAV+CUE]
- 曼丽2021《女人三十2雾之恋》HQCD[WAV+CUE]
- 隔壁老樊.2019-我曾【好听音乐】【FLAC分轨】
- 高林生.1993-牵挂你的人是我【白天鹅】【WAV+CUE】
- 洪卓立.2012-找个懂我的女孩(国专)【英皇娱乐】【WAV+CUE】
- 曼丽2022《女人三十3晚秋》HQCD[WAV+CUE]
- 曼丽2018《女人三十4冬天》HQCD[WAV+CUE]
- 柏菲-《好歌30年壹》限量开盘母带ORMCD[低速原抓WAV+CUE]
- 大自然音乐系列《水舞》[WAV/CUE/分轨][424.3MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]