# 图片预览
# 技术点
swiper 路由 hash
# 介绍
图片预览有挺多插件,但未找到合适本项目的,本项目中需要功能:点击小图时,展示该小图对应的大图,并可左右滑动,切换上一张与下一张大图,最终选择使用 swiper 组件实现。
# 实现解析
点击小图时,显示由 swiper 封装的 photo-swiper 组件,同时路由地址后缀增加 #preview?index=${index} ,以实现点击返回按钮时只关闭预览页面。其中 index 为该小图在图片列表中的索引值,该索引值为 swiper 需要设置显示的索引。
# 相关代码
图片列表页面:用户点击小图
computed: {
    // 显示 photo-swiper 组件,也可以用 watch 监听方式实现
    isShowSwiper() {
        return this.$route.hash.includes("#preview");
    }
}
methods: {
    // 预览图片,路由增加 preview hash 值
    preview(index) {
        this.$router.push(`#preview?index=${index}`);
    }
}
photo-swiper 组件页面
mounted() {
    // 阻止滚动穿透
    this.$preventScroll(true);
    // 获取当前需要展示的图片索引
    this.getInitIndex(); 
    // 初始化 swiper 组件
    this.$nextTick(() => {
        this.initSwiper();
    });
},
beforeDestroy() {
    // 页面销毁前,一定要移除 body 的禁止滚动
    this.$preventScroll(false);
},
methods: {
    // 初始化 swiper
    initSwiper() {
        let _this = this;
        new Swiper(".photo-swiper", {
            lazy: true,                     // 开启图片懒加载
            initialSlide: this.initIndex,   // 路由 hash 值传入的 index 索引
            observer: true,
            observeParents: true,
            watchSlidesVisibility: true,
            on: {
                slideChange: function () {
                    // 此处 this 指向 swiper 示例,activeIndex 为 swiper 滚动后的索引
                    _this.initIndex = this.activeIndex;
                }
            }
        })
    }
}