vue项目结合,vant 实现中轮播图中,点击图片放大图片

发布时间 2023-04-23 13:37:16作者: 中亿丰数字科技

思路:

  1. vant中提供函数 ImagePreview
  2. 给原每一个图片子元素设置点击事件,api中提供 initial-swipe 索引,拿到原图索引
  3. 设置change事件,保存大图切换的对应索引给到自己的 initial-swipe索引中
  4. 设置图片预览切换时,根据切换后的索引,设置原图的位置,大图原图同步
  5. 原图片 swipeTo(i) 切换到指定位置,

代码:

  <!-- 轮播图 -->
      <van-swipe
        class="my-swipe"
        :autoplay="3000"
        indicator-color="white"
        :initial-swipe="index" //自己定义的index值
        @change="onChange"
        ref="mySwipe"
      >
        <van-swipe-item
          v-for="item in imgList"
          :key="item"
          @click="onImgPreView"
        >
          <van-image 
            width="100vw" 
            height="3rem" 
            fit="contain" 
            :src="item" />
        </van-swipe-item>
      </van-swipe>

放大图片

    // 放大图片
    onImgPreView() {
      // 点击轮播图时,通过数据拿到当前索引,根据当前索引创建图片预览,设置默认图片
      const that = this;
      ImagePreview({
        images: this.imgList, //点击后的图片。
        startPosition: this.index, //index默认为0,提供的起始位置
        onChange(i) { 
          // 当图片预览切换时,根据切换后的索引,设置轮播图的位置
          that.$refs.mySwipe.swipeTo(i);
        },
      });
    },
   onChange(index) { //vant提供的索引值
      // 在轮播图切换时,将索引保存到数据中
      this.index = index;
   },

作者:王雅楠