在开发过程中遇到这样一个问题,如何跨组件传递插槽。因为在开发类似树组件的过程中,插槽需要通过外部传递到树的根节点,然后通过根节点依次传递到各个叶子节点。那么如何把根节点的Slot如传递给子组件呢?
我们在开发过程中,希望可以这样实现重新定义叶子节点的结构:

1

2

3

4

5

<data-tree>

 <template v-slot:node="data">

   <div>{{data.title}} - {{data.text}}</div>

  </template>

</data-tree>

那么如何在组件内传递Slot就是一个问题。

嵌套传递

通过固定级别的组件结构里可以通过直接书写<v-slot ...>来传递对应的Slot元素,来实现一层一层的传递。

1

2

3

4

5

6

7

<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传递给下一层。

1

2

3

4

5

h('data-tree-item',{

 scopedSlots: {

    node: props => this.$slots.node(props)

  },

})

这样通过Render子元素就可以接受到对应的Slot,也实现了传递。

动态组件

还有一种方式是通过动态组件,也是认为比较推荐的实现方式,不是通过传递Slot,而是通过子节点主动去获取根节点的Slot对象,然后直接在UI中渲染出来。

为此我们需要创建一个组件来渲染对应的Slot对象。

首先需要获取根节点:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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暴露出来

1

2

3

4

5

6

7

8

9

setup(props) {

    // 获取根节点

    const dataTree = getRootComponent(getCurrentInstance())

    const parentSlots = dataTree?.slots

    const nodeTemplate = parentSlots?.node as any

    return {

      nodeTemplate

    }

  }

这时候我们需要一个组件来渲染暴露出来的Slot:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

components: {

    TemplateContainer: {

      functional: true,

      props: {

        template: {

          type: Function

        },

        data: {

          type: Object

        }

      },

      render: (props, ctx) => h('div', [props.template(props.data)])

    }

  }

好了现在该准备的都准备好了,可以去实现UI的显示了:

1

2

3

4

5

6

7

8

<template-container

          v-if="nodeTemplate"

          :template="nodeTemplate"

          :data="node">

</template-container>

<template v-else>

    {{ node.label }}

</template>

这样我们就实现了类似下面定义Slot的传递,也解决了我们跨组件传递Slot的问题。

1

2

3

<slot :data="node" name="node">

 {{ node.label }}

</slot>

本文使用的是Vue 3的事例,Vue 2也是相同的概念,在Vue 3中除了使用getRootComponent来查询跟节点,也可以使用Provide/Inject来将Slot主动传递给子节点。

转载于:Vue如何跨组件传递Slot的实现_vue.js_脚本之家

Logo

鸿蒙生态一站式服务平台。

更多推荐