响应式滚动图懒加载 element ui el-carousel 组件优化代码

版权声明:本文为蔡俊锋博主原创文章,未经蔡俊锋博主允许不得转载。 https://blog.csdn.net/caijunfen/article/details/84561504

 响应式滚动图懒加载 element ui  el-carousel 组件优化代码 

懒加载插件vue-lazyload

//main.js
import VueLazyload from 'vue-lazyload'

Vue.use(VueLazyload, {
    preLoad: 1.3,
    attempt: 1, // 加载图片数量
    listenEvents: ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove']
})
<template>
    <el-carousel :interval="3000" indicator-position="none" id="el-carousel">
        <el-carousel-item v-for="img in list" :key="img">
            <img v-lazy="img">
        </el-carousel-item>
    </el-carousel>
</template>

<script>
export default {
    data() {
        return {
            bannerHeight: 700,
            screenWidth: 1920,
            list: [
                //banner 图地址
                "http://ip/image/home/banner1.jpg",
                "http://ip/image/home/banner2.jpg",
                "http://ip/image/home/banner3.jpg",
                "http://ip/image/home/banner4.jpg"
            ]
        };
    },

    beforeMount() {
        this.screenWidth = this.getwidth();
        //图片                高 / 宽  700 / 1920
        this.bannerHeight = (700 / 1920) * this.screenWidth - 50;
        console.log('bannerHeight', bannerHeight)
    },

    mounted() {
        const that = this;
        document.getElementById("el-carousel").style.height =
            this.bannerHeight + "px";
        //监听浏览器窗口大小改变
        window.addEventListener(
            "resize",
            function () {
                that.screenWidth = that.getwidth();
                that.setSize();
            },
            false
        );
    },
    methods: {
        getwidth() {
            var width =
                window.innerWidth ||
                document.documentElement.clientWidth ||
                document.body.clientWidth;
            return width;
        },

        setSize: function () {
            this.bannerHeight = (700 / 1920) * this.screenWidth - 50;
            document.getElementById("el-carousel").style.height =
                this.bannerHeight + "px";
        }
    }
};
</script>

<style>
.el-carousel__container {
    height: 100% !important;
}

img {
    display: inline-block;
    height: auto;
    max-width: 100%;
}
</style>

猜你喜欢

转载自blog.csdn.net/caijunfen/article/details/84561504