美文网首页
Vue3 在template中渲染vnode

Vue3 在template中渲染vnode

作者: 般犀 | 来源:发表于2022-10-23 23:07 被阅读0次

    遇到一个功能点,需要遍历<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

    相关文章

      网友评论

          本文标题:Vue3 在template中渲染vnode

          本文链接:https://www.haomeiwen.com/subject/fvewzrtx.html