分类: javascript 545阅读阅读模式
数据出自 https://swiperjs.com/vue
根据实际前后数据更新时,autoplay并未执行,需要通过初始化实例后进行 start()
示例如下:
- <template>
- <swiper
- class="swiper-box"
- :modules="swiperModules"
- slides-per-view="auto"
- direction="vertical"
- :speed="2000"
- :free-mode="true"
- :observer="true"
- :autoplay="{
- delay: 0,
- disableOnInteraction: false,
- }"
- @swiper="handleSwiper"
- @slide-change="handleSlideChange">
- <swiper-slide class="swiper-item" v-for="(item, index) in datalist" :key="index">
- {{ item }}
- </swiper-slide>
- </swiper>
- </template>
- <script lang="ts">
- import type { Swiper as SwiperType } from 'swiper'
- import { defineComponent, ref, onMounted, nextTick } from 'vue'
- import { Autoplay } from 'swiper'
- import { Swiper, SwiperSlide } from 'swiper/vue'
- import 'swiper/css'
- import 'swiper/css/autoplay'
- import 'swiper/css/navigation'
- import 'swiper/css/pagination'
- export default defineComponent({
- name: 'EXP',
- components: { Swiper, SwiperSlide },
- // props: { },
- setup() {
- const datalist = ref<number[]>([])
- const swp = ref<SwiperType | null>(null)
- const swiperModules = [Autoplay]
- function getRandom(min, max) {
- return Math.floor(Math.random() * (max - min + 1) + min)
- }
- function getRandomArr() {
- const res: number[] = []
- const len = parseInt(String(Math.random() * 100))
- for (let i = 0; i < len; i++) {
- res.push(getRandom(1, 1000))
- }
- return res
- }
- function initData() {
- datalist.value = getRandomArr()
- updateSwiper()
- setTimeout(() => {
- initData()
- }, 10000)
- }
- function handleSwiper(swiper: SwiperType) {
- // init
- swp.value = swiper
- }
- function handleSlideChange(swiper: SwiperType) {
- // change
- console.log('swiper slide change ==>', swiper)
- }
- function updateSwiper() {
- const swpUp = swp.value as SwiperType
- if (!swp.value) {
- return
- }
- nextTick(() => {
- swpUp.updateSlides()
- swpUp.slideTo(0, 0)
- swpUp.autoplay?.start()
- swpUp.update()
- })
- }
- onMounted(() => {
- setTimeout(() => {
- initData()
- }, 3000)
- })
- return {
- datalist,
- handleSwiper,
- handleSlideChange,
- swiperModules,
- }
- },
- })
- </script>
- <style lang="scss">
- .swiper {
- &-box {
- width: 100%;
- height: 300px;
- }
- &-item {
- width: 100%;
- height: 30px;
- border-bottom: 1px solid #eee;
- }
- }
- </style>