響應式滾動圖懶載入 element ui el-carousel 元件優化程式碼
阿新 • • 發佈:2019-01-13
響應式滾動圖懶載入 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>