我有一个通过index.html中的脚本连接的swiper组件
<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-element-bundle.min.js"></script>
这是刷卡器本身:
<swiper-container class="swiper" :slides-per-view="5" :space-between="20">
<swiper-slide v-for="(film, index) in films" :key="index" class="swiper-slide">
<div class="swiper-slide__container" @click="selectFilm(film)">
<img class="swiper__img" :src="film.imgUrl" :alt="film.imgAlt">
<a class="swiper-link">{{ film.link }}</a>
</div>
</swiper-slide>
</swiper-container>
而且我不知道如何使其适应较小的屏幕。即值
:slides-per-view="5"
做更少的事情。例如至少3个。或者根本没有办法做到这一点,您将不得不以某种方式隐藏它,或者只是在窗口的特定宽度处更改它。
如果有人遇到过并且知道问题的解决办法,我将非常感激
我通过代码尝试过,但是无论你在那里写什么,仍然会给出错误,并且通过媒体查询我认为不可能更改此属性
您可以使用
vue-responsiveness
npm 包(文档此处)例如:
main.js:
import { VueResponsiveness } from 'vue-responsiveness'
app.use(VueResponsiveness)
应用程序.vue:
<template>
<swiper-container class="swiper" :slides-per-view="slidesPerView" :space-between="20">
<swiper-slide v-for="(film, index) in films" :key="index" class="swiper-slide">
<div class="swiper-slide__container" @click="selectFilm(film)">
<img class="swiper__img" :src="film.imgUrl" :alt="film.imgAlt">
<a class="swiper-link">{{ film.link }}</a>
</div>
</swiper-slide>
</swiper-container>
</template>
<script setup>
import { computed } from 'vue'
import { useMatches } from 'vue-responsiveness'
const matches = useMatches()
const slidesPerView = computed(() => {
switch(matches.current)
{
case 'xxl': return 7;
case 'xl': return 5;
case 'md': return 3;
case 'sm': return 2;
case 'xs': return 1;
default: return 0;
}
})
</script>
在这种情况下,您可以为每个断点指定幻灯片计数。
您还可以为
space-between
属性创建类似的计算属性。
如果你不使用ES并在index.html中编写应用程序,你可以使用此代码而不是使用npm包:
const breakpoint = ref('')
onMounted(() => {
updateBreakpoint()
window.addEventListener('resize', updateBreakpoint);
})
onUnmounted(() => {
window.removeEventListener('resize', updateBreakpoint);
});
const updateBreakpoint = () => {
if (window.matchMedia('(max-width: 576px)').matches) {
breakpoint.value = 'xs';
} else if (window.matchMedia('(max-width: 768px)').matches) {
breakpoint.value = 'sm';
} else if (window.matchMedia('(max-width: 992px)').matches) {
breakpoint.value = 'md';
} else if (window.matchMedia('(max-width: 1200px)').matches) {
breakpoint.value = 'lg';
} else {
breakpoint.value = 'xl';
}
};
然后在
breakpoint
计算属性中使用 slidesPerView
变量
如果您还有任何疑问,请告诉我。
ps:如果您觉得有用,请不要忘记给我的帖子点赞并将其标记为答案