Renderless Component

从名字上能看出这个组件本身跟UI没有关系,所以叫做Renderless。它所作的事情是把一些计算逻辑抽离出来,便于复用。其实我有一点疑惑,我既然有了Composition,我为什么还要用Renderless Component呢?在我看来它们两个的场景很相似,而我更喜欢Composition。不管怎么样,先介绍一下Renderless Component吧。

它的大致代码结构是这样的:

// MyRenderlessComponent.ts
export default MyRenderlessComponent {
  setup(props, { slot }) {
    // 读取props中的值

    // 根据props中的值进行运算,获取新的值(计算属性或Ref)

    return slot.default({
      // 把计算得到的值传递出去
    })
  }
}
<template>
  <MyRenderlessComponent :some-prop="xxx" v-slot="{ 传递出来的值 }">使用传递出来的值
  </MyRenderlessComponent>
</template>

<script setup lang="ts">
const xxx = ref('');
</script>


评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注