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