Swiper 轮播
示例
轮播内容
<script lang="ts">
const colors = ['#ace0ff', '#bcffbd', '#e4fabd', '#ffcfac', 'pink']
let value = $state(0)
</script>
{#snippet items(colors: string[])}
{#each colors as color, index}
<div
class="flex items-center justify-center text-white"
style="background-color: {color}; font-size: 48px;"
>
<span>{index + 1}</span>
</div>
{/each}
{/snippet}
横向
基础用法
<Swiper style="height: 120px">
{@render items(colors.slice(0, 2))}
</Swiper>
圆角+回弹
<Swiper style="height: 120px; border-radius: 8px" bounce>
{@render items(colors.slice(0, 3))}
</Swiper>
自动播放
<Swiper style="height: 120px" autoplay>
{@render items(colors.slice(0, 4))}
</Swiper>
自动播放+循环
<Swiper style="height: 120px" autoplay loop>
{@render items(colors)}
</Swiper>
手动控制+循环
<Swiper bind:value style="height: 120px" loop>
{@render items(colors)}
</Swiper>
<Space class="bg-white p-4" block>
{#each colors, index}
<Button onclick={() => (value = index)}>{index + 1}</Button>
{/each}
</Space>
纵向
基础用法
<Swiper style="height: 120px" direction="vertical">
{@render items(colors.slice(0, 2))}
</Swiper>
指示器
指示器颜色
<Swiper
style="height: 120px"
--sunp-color="rgba(0, 0, 0, 0.4)"
--sunp-active-color="#ffc0cb"
--sunp-size="10px"
--sunp-active-size="30px"
--sunp-radius="15px"
--sunp-gap="8px"
>
{@render items(colors)}
</Swiper>
指示器在滑块外面
<Swiper
class="bg-gray-100"
style="height: 120px; border-radius: 6px"
bounce
--sunp-radius="8px"
--sunp-padding="0 0 16px"
>
{@render items(colors)}
</Swiper>
自定义指示器
<Swiper style="height: 120px">
{@render items(colors)}
{#snippet indicator(total: number, value: number)}
<div
style="position: absolute; top: 8px; right: 8px; padding: 0.25rem 0.5rem;
border-radius: 5px; background-color: rgb(75 85 99 / 0.5);
font-size: 14px; color: white"
>
{value + 1} / {total}
</div>
{/snippet}
</Swiper>
无指示器
<Swiper style="height: 120px" autoplay loop>
{@render items(colors)}
{#snippet indicator()}{/snippet}
</Swiper>
特殊用法
<script lang="ts">
let visible = $state(false)
</script>
<Button onclick={() => (visible = true)}>显示弹出层</Button>
<Popup bind:visible class="h-full" destroyOnClose>
<Swiper class="h-full">
{@render items(colors.slice(0, 2))}
<div class="flex items-center justify-center bg-white text-white">
<Button onclick={() => (visible = false)}>开始使用</Button>
</div>
</Swiper>
</Popup>
Swiper
属性
属性 |
说明 |
类型 |
默认值 |
value |
当前播放的索引 |
number |
$bindable(0) |
direction |
方向 |
'horizontal' | 'vertical' |
'horizontal' |
autoplay |
自动切换 |
boolean |
false |
autoplayInterval |
自动切换的时间间隔(毫秒) |
number |
3000 |
loop |
是否循环。子元素数量大于 2 时生效 |
boolean |
false |
bounce |
拖动超出区域时启用回弹效果。 仅在非 loop 模式下,且子元素数量大于 1 时生效 |
boolean |
false |
indicator |
自定义指示器 |
Snippet<[total: number, value: number]> |
undefined |
事件
事件 |
说明 |
类型 |
onChange |
切换时触发 |
(value: number) => void |
onClick |
点击面板时触发 |
(value: number) => void |
CSS 变量
属性 |
说明 |
默认值 |
--sunp-padding |
轮播轨道的边距 |
0 |