在vue项目中使用v-show控制元素隐藏导致swiper的轮播图及分页无法正常显示

一、需求问题

在之前的项目开发中,使用了swiper插件。由于是vue项目,对于swiper的轮播图我们使用了v-show命令,进行动态隐藏与显示。只有当点击进行一些操作以后,swiper的轮播图才会显示出来。但是,在使用v-show命令以后,swiper的轮播图显示和分页不正常,样式出现问题,无法正常显示。

二、需求分析

swiper的配置中,我们一开始进行配置了paginationpaginationTypepagination的配置是分页器容器的CSS选择器或HTML标签,paginationType的配置是分页器样式类型。但是,一旦使用v-show以后,就会出现问题。我们可以先配置observeParents,这样将observe应用于Swiper的父元素,Swiper的父元素变化时,Swiper也会及时更新。然后再配置启动动态检查器,当改变swiper的样式,比如隐藏或者显示,以及修改swiper的子元素时,自动初始化swiper。通过这两个设置,就可以完美解决这种问题了。

三、需求实现

  1. 实例代码显示如下:
<template>
    <div class="container" @click="handleClick">
        <div class="wrapper">
            <swiper :options="swiperOptions">
                <swiper-slide v-for="(item,index) of imgs" :key="index">
                    <img  class="gallary-img" :src="item" />
                </swiper-slide>
                <div class="swiper-pagination"  slot="pagination"></div>
            </swiper>
        </div>
    </div>
</template>

<script>
export default {
  name: 'CommonGallary',
  data () {
    return {
      swiperOptions: {
        pagination: '.swiper-pagination',
        paginationType: 'fraction',
        observeParents: true,
        observer: true
      }
    }
  },
  props: {
    imgs: {
      type: Array,
      default () { return [] }
    }
  },
  methods: {
    handleClick () {
      this.$emit('close')
    }
  }
}
</script>

<style lang="stylus" scoped>
    .container >>> .swiper-container
        overflow: inherit
    .container
        display: flex
        flex-direction: column
        justify-content: center
        z-index: 99
        position: fixed
        left: 0
        right: 0
        top: 0
        bottom: 0
        background: #000
        .wrapper
            height: 0
            width: 100%
            padding-bottom: 100%
            .gallary-img
                width: 100%
            .swiper-pagination
                color : #fff
                bottom: -1rem
</style>
发布了146 篇原创文章 · 获赞 34 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42614080/article/details/103786890