金狮镖局 Design By www.egabc.com

在开发过程中遇到这样一个问题,如何跨组件传递插槽。因为在开发类似树组件的过程中,插槽需要通过外部传递到树的根节点,然后通过根节点依次传递到各个叶子节点。那么如何把根节点的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主动传递给子节点。

标签:
Vue,跨组件传递Slot,Vue,跨组件传递

金狮镖局 Design By www.egabc.com
金狮镖局 免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
金狮镖局 Design By www.egabc.com

评论“Vue如何跨组件传递Slot的实现”

暂无Vue如何跨组件传递Slot的实现的评论...

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?