搜索
使用Vue插槽元素在模板循环中进行渲染
P粉514458863
P粉514458863 2023-09-15 10:37:00
[Vue.js讨论组]

我正在尝试通过使用插槽将幻灯片的HTML传递给一个组件,然后将它们渲染为另一个组件

// carousel.blade.php
<my-carousel>
<template v-slot:slides>
    <div>slide 1</div>
    <div>slide 2</div>
</template>
</my-carousel>

MyCarousel 然后将每个 <div> 转换为 Swiper 幻灯片。

我可以使用 slots.slides() 循环遍历传递到插槽中的元素。我的问题是,如何在 swiper-slide 内部渲染该元素的内容?

// MyCarousel.vue
<script setup>
import { useSlots } from "vue";

import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';

const slots = useSlots();

console.log(slots.slides());
</script>

<template>
    <div>
        <swiper>
            <swiper-slide v-for="(slide, key) in slots.slides()">
                <!-- 渲染当前幻灯片/插槽内容 -->
            </swiper-slide>
        </swiper>
    </div>
</template>

<style scoped>
</style>

我知道我可以直接在 Blade 视图中使用 Swiper,但我正在尝试避免这样做,只有在包装在 Vue 组件中时才将幻灯片转换为 。其余时间它将使用普通的 HTML。

P粉514458863
P粉514458863

全部回复(1)
P粉938936304

典型的情况,我在发帖后找了很久才找到解决方案。而且它非常简单。

循环中的每个slide都可以呈现为动态的<component>

<script setup>
import { useSlots } from "vue";

import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';

const slots = useSlots();

console.log(slots.slides());
</script>

<template>
    <div>
        <swiper>
            <swiper-slide v-for="(slide, key) in slots.slides()" v-bind="props">
                <component :is="slide" />
            </swiper-slide>
        </swiper>
    </div>
</template>

<style scoped>
</style>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号