Vue3 在template中渲染vnode

遇到一个功能点,需要遍历<slot>中传入的vnode,在每个vnode外面套个div再渲染出来。找了半天怎么用<template>把vnode渲染出来。

// 父组件
<template>
  <child-component>
     <div>1</div>
     <div>2</div>
  <child-component>
</template>
// 子组件
<script setup>
import { useSlots } from 'vue';
const slots = useSlots();
const children = ref([]);
if (slots.default) {
  children.value = slots.default();
}
</script>
<template>
  <div>
    <div v-for="(child, index) in children" :key="index">
      <component :is="child"></component> // 重点是这里
    </div>
  </div>
</template>

参考文章:
https://stackoverflow.com/questions/49352525/can-you-render-vnodes-in-a-vue-template
https://segmentfault.com/q/1010000020205251

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、对于MVVM的理解 Model:代表数据模型,也可以在Model中定义数据修改和操作的业务逻辑。View: 代...
    你瞅瞅你写的bug阅读 3,177评论 0 1
  • 1 Webpack 1.1 概念简介 1.1.1 WebPack是什么 1、一个打包工具 2、一个模块加载工具 3...
    Kevin_Junbaozi阅读 11,768评论 0 16
  • 2020/03/30 周一 #[http://fe.zuo11.com/daily/2020-03.html#js...
    抓猹吃瓜阅读 1,839评论 0 1
  • 前几天想学学Vue中怎么编写可复用的组件,提到要对Vue的render函数有所了解。可仔细一想,对于Vue的ren...
    kangaroo_v阅读 116,344评论 13 171
  • 模板渲染过程在实际使用vue的过程可能并不需要太深理解,但就vue来说,这些底层思想可以更好地让我们理解这个框架,...
    指尖跳动阅读 14,915评论 1 15