Skip to content

插槽内容问题

javascript
/**
 * 插槽内容
 * @type {Array}
 * @description
 * 轮播图接收的 slot 可能是由 v-for 生成的卡片或者是静态内容书写的卡片。
 * 当 slot 是由 v-for 生成的卡片的时候,useSlots().default()[0].children 会收到 type 属性为 symbol 的 VNode 虚拟节点、
 * 而该节点下的 children 数组才是轮播图需要接收的卡片。
 * 当 slot 是静态内容书写的卡片的时候,useSlots().default()[0].children 则会直接收到 children 数组。
 * 为了统一处理,我们需要对 useSlots().default()[0].children 进行展平处理。
 * 使用 flatMap 方法,将 VNode 虚拟节点下的 children 数组展平。
 * 此时我们就可以得到一个统一的卡片数组。
 */
const carouselItems = useSlots().default()[0].children.flatMap((child) => (typeof child.type !== 'symbol' ? [child] : child.children));