设置responsive属性
ant-design-vue 3.0 的Carousel组件增加了responsive的属性,通过媒体查询和 CSS 样式来实现响应式布局,使其响应不同的视口尺寸
<template>
<a-carousel :autoplay="true" :dots="true" :responsive="responsiveSettings">
<a-carousel-item>
<!-- 第一个轮播项内容 -->
</a-carousel-item>
<a-carousel-item>
<!-- 第二个轮播项内容 -->
</a-carousel-item>
<!-- 添加更多的轮播项 -->
</a-carousel>
</template>
<script>
export default {
data() {
return {
responsiveSettings: [
{
breakpoint: 575,
settings: {
dots: false,
slidesToShow: 1,
slidesToScroll: 1
}
},
{
breakpoint: 768,
settings: {
dots: false,
slidesToShow: 1,
slidesToScroll: 1
}
},
{
breakpoint: 992,
settings: {
dots: false,
slidesToShow: 2,
slidesToScroll: 1
}
},
{
breakpoint: 1200,
settings: {
dots: false,
slidesToShow: 2,
slidesToScroll: 1
}
},
{
breakpoint: 1600,
settings: {
dots: false,
slidesToShow: 4,
slidesToScroll: 1
}
}
]
};
}
};
</script>
在 responsiveSettings
中,我们为每个屏幕尺寸定义了一个对象,包括断点(breakpoint)和具体的设置(settings)。例如,对于小屏幕(xs),我们设置了一个最大宽度为 575 像素的断点,并指定显示 1 个轮播项,滚动 1 个轮播项。
监听Window的resize事件,动态设置slidesToShow属性
<template>
<a-carousel
:autoplay="true"
:dots="true"
:slidesToScroll="1"
:slidesToShow="slidesToShow"
>
<a-carousel-item>
<!-- 第一个轮播项内容 -->
</a-carousel-item>
<a-carousel-item>
<!-- 第二个轮播项内容 -->
</a-carousel-item>
<!-- 添加更多的轮播项 -->
</a-carousel>
</template>
<script>
export default {
data() {
return {
slidesToShow: 4,
}
},
mounted() {
window.onresize = () => {
const width = document.body.clientWidth
if (width < 992) {
this.slidesToShow = 1
} else if (width >= 992 && width < 1600) {
this.slidesToShow = 2
} else {
this.slidesToShow = 4
}
}
},
}
</script>