基于swiper5做的轮播图

文章介绍了如何使用Vue.js和Swiper库创建一个动态的图片轮播组件,包括懒加载、主题切换、滚动模式控制和IE浏览器兼容性处理。同时,还展示了如何通过axios获取数据和实现页面导航功能。
摘要由CSDN通过智能技术生成
<template>
  <div class="slideshow" :class="{'showBottomBtn':pageMode}">
    <div class="swiper-container">
        <div class="swiper-wrapper">
            <div class="swiper-slide" v-for="(item,index) in picList" :key="index">
              <div class="img swiper-zoom-container imgOver" >
                <img :style="'height: ' + item.height + 'px;width:' + item.width +'px;'" :data-src="item.path" id="image" class="swiper-lazy"/>
                <div class="swiper-lazy-preloader"></div>
              </div>
              <div class="maskLayer abottom"  v-if="item.description">
                <div class="content">
                    <label class="info" v-if="item.description.length > 150" @click.stop="showInfo(item.description)">{{ item.description.substring(0,150) }}...</label>
                    <label class="info" v-else>{{ item.description }}</label>
                </div>
              </div>
            </div>
        </div>
        <div class="swiper-button-prev" @click="prev" v-if="pageMode"></div>
        <div class="swiper-button-next" @click="next" v-if="pageMode"></div>
    </div>
    <el-dialog top="20vh" class="abottom" :visible.sync="dialogInfo" @close="closeDialog">
        <div class="dia-info">{{ info }}</div>
    </el-dialog>
    <div class="theme" v-if="showBtn">
        <div class="content">
            <div class="theme-item" id="menuClick" :class="initId == t.id? 'active': ''" v-for="(t,i) in theme" :key="i" @click.stop="changeTheme(t)">{{ t.name }}</div>
            <div class="theme-item" :class="initId==-99? 'active': ''" id="menuClick" @click.stop="changeTheme({id: -99})">全部</div>
            <div class="theme-item full-mode"  id="menuClick" @click.stop="fullBtn">{{ fullScreenType }}</div>
            <div class="theme-item full-mode"  id="menuClick" @click.stop="prevNext">{{ pageMode?'底部翻页':'左右翻页' }}</div>
        </div>
    </div>
    <div class="mask-click" v-else @click="showBottom"></div>
    <div class="footer" v-if="!pageMode">
        <div class="footBtn" @click.stop="first">首页</div>
        <div class="footBtn" @click.stop="prev">上一页</div>
        <div class="footBtn" @click.stop="next">下一页</div>
        <div class="footBtn" @click.stop="last">尾页</div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import "swiper/css/swiper.css";
import Swiper from 'swiper'
import objectFitImages from 'object-fit-images'
export default {
    data() {
        return {
            showBtn: false,
            dialogInfo: false,
            info: '',
            theme: [],
            picList: [],
            picInfo: [],
            swiper: null,
            searchForm: {
                pager: {
                    pageSize: 10,
                    page: 1,
                    totalCount: 0,
                },
            },
            containerWidth: '',
            containerHeight: '',
            isIE: Boolean,
            type: 0,
            initId: '',
            fullScreenType: '全屏模式',
            setTime: {},
            timeOut: null, // 菜单计时
            initTimeOut: null, // 初始化计时
            timer: null,
            pageMode: true,
        }
    },
    created() {
        this.isIE = /MSIE|Trident/.test(window.navigator.userAgent)
        objectFitImages()
        this.type = this.$route.query.type
        this.getSet()
        this.getScreen()
        this.getTheme()
        this.timer = setInterval(()=> {
            this.getSet()
        }, 5 * 60 * 1000)
    },
    computed: {
        autoplayDelay() {
            return this.setTime.no3;
        },
    },
    mounted() {
        document.addEventListener('touchmove', function(e) {
            e.preventDefault();
        }, { passive: false });
    },
    methods: {
        fullBtn() {
            const element = document.documentElement;
            if (document.fullscreenElement || document.webkitFullscreenElement) {
                this.fullScreenType = '全屏模式'
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
            } else {
                this.fullScreenType = '退出全屏'
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.webkitRequestFullscreen) {
                    element.webkitRequestFullscreen();
                }
            }
            this.hideMenu()
            this.initShow()
        }, 
        getSet() {
            axios({
                url: `${home}/net/showNo`,
                method: 'get',
            }).then(res=> {
                if(res.result.success) {
                    this.setTime = res.data
                    this.initSwiper()
                }
            })
        }, 
        hideMenu() {
            clearTimeout(this.timeOut)
            this.timeOut = setTimeout(()=> {
                this.showBtn = false
            }, this.setTime.no2)
        },
        prevNext() {
            this.pageMode = !this.pageMode
            this.initSwiper()
            this.hideMenu()
            this.initShow()
        },
        initShow() {
            clearTimeout(this.initTimeOut)
            this.initTimeOut = setTimeout(()=> {
                this.getPicList()
            }, this.setTime.no1)
        },
        initSwiper() {
            if (this.swiper) {
                this.swiper.destroy();
                this.swiper = null;
            }
            this.swiper = new Swiper('.swiper-container', {
                mode:'horizontal',
                loop: true,
                autoplay: {
                    delay: this.autoplayDelay,
                    disableOnInteraction: false,
                },
                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },
                touchEventsTarget: 'container',
                lazy: {
                    loadPrevNext: true,
                },
                speed: 600,
                mousewheel: true,
                keyboard: true,
                pagination: false,
                allowTouchMove: true,         
            },);
            this.swiper.lazy.load();
            this.swiper.update();
        },
        showBottom() {
            this.showBtn = true
            this.hideMenu()
            this.initShow()
        },
        getTheme() {
            axios({
                url: `${home}/net/showZts`,
                method: "get",
            }).then(res => {
                if(res.result.success) {
                    this.theme = res.data
                    if(!this.$route.query.type) {
                        this.initId =  res.data[0].id
                        sessionStorage.setItem('initId', res.data[0].id)
                    } else {
                        this.initId =  res.data[Number(this.$route.query.type) - 1].id
                    }
                    this.getPicList()
                }
            });
        },
        async getPicList(id) {
            if(id) {
                this.initId = id
            } else if(this.$route.query.type) {
                this.initId = Number(this.$route.query.type)
            } else {
                this.initId = sessionStorage.getItem('initId')
            }
            await axios({
                url: `${home}/net/findFiles`,
                method: "POST",
                data: {
                    parentId: this.initId
                }
            }).then(async res => {
                this.picList = []
                await Promise.all(res.data.map(async (image)=> {
                    let {img, width, height} = await this.getSize(config.resPre + image.path)
                    if (height > width) {
                        let float = width / height
                        height = this.containerHeight
                        width = float * height
                    } else {
                        let float = height / width
                        width = this.containerWidth
                        height = float * width
                    }
                    this.picList.push({
                        ...image,
                        path: img.src,
                        width,
                        height
                    })
                }))
                this.$forceUpdate()
                this.$nextTick(() => {
                    this.initSwiper()
                }) 
            });
        },
        getSize(src) {
            const imgData = src
            const img = new Image();
            return new Promise(resolve => {
                img.onload = ()=> {
                    const { width, height } = img;
                    resolve({ img, width, height})
                };
                img.src = imgData;
            })
        },
        getScreen() {
            this.containerWidth = window.screen.width 
            this.containerHeight = window.screen.height
        }, 
        changeTheme(item) {
            this.picList.length = 0
            this.getPicList(item.id)
            this.showBtn = false
            this.hideMenu()
            this.initShow()
        },
        first() {
            this.swiper.slideTo(1)
            this.restart()
            this.initShow()
        },
        prev() {
            this.swiper.slidePrev()
            this.restart()
            this.initShow()
        },
        next() {
            this.swiper.slideNext()
            this.restart()
            this.initShow()
        },
        last() {
            this.swiper.slideTo(this.picList.length)
            this.restart()
            this.initShow()
        },
        restart() {
            if(this.isIE) {
                this.swiper.autoplay.start()
            }
        },
        showInfo(info) {
            this.info = info
            this.dialogInfo = true
            this.swiper.autoplay.stop()
            this.initShow()
        },
        closeDialog() {
            this.info = ''
            this.dialogInfo = false
            this.swiper.autoplay.start()
            this.initShow()
        },
    },
    beforeDestroy() {
        clearInterval(this.timer);
        this.timer = null;
    },
}
</script>

<style lang="scss" scoped>
.slideshow.showBottomBtn {
    .abottom {
        bottom: 0 !important;
    }
}
.slideshow {
    width: 100%;
    height: 100%;
    .swiper-container {
        height: 100%;
        width: 100%;

        .swiper-slide {
            position: relative;
            .imgOver {
                width: 100%;
                height: 100%;
                #image {
                    object-fit: contain;
                    font-family: 'object-fit: contain;';
                }
            }
        }
        .maskLayer {
            position: absolute;
            left: 0;
            bottom: 60px;
            width: 100%;
            height: 100px;
            // background-color: #c6e1f257;
            background: #c6e1f29e;
            z-index: 999;
            .content {
                width: 100%;
                height: 100px;
                color: #000;
                font-size: 20px;
                text-align: left;
                margin: auto;
                line-height: 100px;
                padding: 0 25px;
                box-sizing: border-box;
                .info {
                    display: inline-block;
                    vertical-align: middle;
                    line-height: 26px;
                    user-select: none;
                }
            }
        }
        // .abottom {
        //     bottom: 0 !important;
        // }
        
    }

    .mask-click {
        width: 100%;
        height: 60px;
        position: fixed;
        left: 0;
        top: 0;
        z-index: 999 !important;
    }

    /deep/.el-dialog {
        position: absolute;
        left: 50%;
        bottom: 10px;
        transform: translateX(-50%);
        background: #FFF;
    }
    /deep/.el-dialog__headerbtn .el-dialog__close {
        color: red;
    }
    /deep/.el-dialog__headerbtn {
        font-size: 22px;
    }

    .dia-info {
        padding: 10px 20px 20px 20px;
        box-sizing: border-box;
        font-size: 20px;
        color: #000;
    }

    .theme {
        position: fixed;
        top: 0;
        left: 0;
        height: 60px;
        width: 100%;
        background: #c6e1f257;
        background: #c6e1f2f7;
        z-index: 999;
        .content {
            width: 80%;
            height: 100%;
            margin: 0 auto;
            overflow-x: scroll;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0 20px;
            box-sizing: border-box;
            .theme-item {
                border: 1px solid #0f83cc;
                border-radius: 5px;
                color: #0f83cc;
                margin-right: 40px;
                padding: 8px 15px;
                box-sizing: border-box;
                cursor: default;
            }
            .theme-item:last-child {
                margin-right: 0;
            }
            /deep/.el-button:focus, .el-button:hover {
                color: #044066;
            }
            .full-mode {
                color: #fff;
                background: #0f83cc;
            }
        }
        .content::-webkit-scrollbar {
            display: none
        }
    }
    .footer {
        position: fixed;
        bottom: 0;
        left: 0;
        height: 60px;
        width: 100%;
        // background: #c6e1f257;
        background: #c6e1f29e;
        // padding: 0 600px;
        // box-sizing: border-box;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999;
        .footBtn {
            background: #0f83cc;
            color: #FFF;
            padding: 8px 15px;
            box-sizing: border-box;
            border-radius: 5px;
            margin-right: 50px;
            cursor: default;
        }
        .footBtn:last-child {
            margin-right: 0;
        }
    }
    .active {
        background: #0f83cc;
        color: #FFF !important;
    }
}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值