swiper实现大图预览功能

首先安装swiper插件:6.8.4版本

npm install swiper --save

<template>
  <div>
    <div class="img">
      <img v-for="(img,index) in srcList"
           :src="img"
           alt=""
           :key="index"
           @click="canView(index)">
    </div>
    <div class="swiper-container"
         @click="closeView"
         v-show="isView">
      <div class="swiper-wrapper">
        <div class="swiper-slide"
             v-for="(img,index) in srcList"
             :key="index">
          <img :src="img"
               alt="" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Swiper from 'swiper';
import 'swiper/swiper-bundle.css'
export default {
  data () {
    return {
      Swiper: null,
      isView: false,
      index: 0,
      srcList:['img1.png','img2.png']
    };
  },
  methods: {
    initSwiper () {
      this.Swiper = new Swiper(".swiper-container", {
        direction: 'horizontal',
        loop: false,
        observer: true, //修改swiper自己或子元素时,自动初始化swiper 
        observeParents: true, //修改swiper的父元素时,自动初始化swiper
        initialSlide: this.index,
      });
    },
    canView (index) {
      this.index = index
      this.$nextTick(() => {
        this.initSwiper()
        this.isView = true
      })
    },
    closeView () {
      this.index = 0
      this.isView = false
    }

  },
  mounted () {
    let _this = this
    window.addEventListener("popstate", function (e) {
      // alert("监听到返回按钮事件啦");
      _this.isView = false
    }, false);
  },
};
</script>
<style lang="scss" scoped>
.img {
  display: grid;
  grid-template-columns: 5.27rem 5.27rem 5.27rem 5.27rem;
  align-items: start;
  justify-items: start;
  grid-auto-flow: row;
  img {
    border-radius: 0.65rem;
    width: 4.49rem;
    height: 4.49rem;
    margin-right: 0.78rem;
    margin-bottom: 0.78rem;
  }
}
.swiper-container {
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10000;
  img {
    width: 100%;
    height: auto;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
 

  

posted @ 2021-12-10 14:32  chicidol  阅读(572)  评论(0编辑  收藏  举报