element-ui中輪播圖自適應圖片高度

哈哈,久違了各位。我又回來了,最近在作畢設,因此不免會遇到不少問題,須要解決不少問題,在萬能的博友幫助下,終於解決了Element-ui中輪播圖的圖片高度問題,話很少說上代碼。javascript

那個axios的使用不重要,大體思路就是頁面渲染前拿到當前窗口的寬度*圖片比例給輪播圖一個初始的高度,當窗後大小發生變化時,監聽事件裏將輪播圖高度從新賦值便可,再次感謝兩位博友的幫助java

<template>
    <div v-if="imgurl">
      <el-carousel :height="imgHeight+'px'" trigger="click">
        <el-carousel-item v-for="(item,index) in imgurl" :key="index">
          <img ref="image" style="width:100%;" :src="item" alt="輪播圖" />
        </el-carousel-item>
      </el-carousel>
    </div>
</template>
<script>
// 引入axios
import axios from "axios";
export default {
  name: "First",
  data() {
    return {
      imgurl: [],
      imgHeight: ""
    };
  },
  methods: {
    imgLoad() {
      this.$nextTick(function() {
        // 獲取窗口寬度*圖片的比例,定義頁面初始的輪播圖高度
        this.imgHeight = document.body.clientWidth*1/4
      });
    },
    getImgUrl() {
      axios
        .get("/carousel")
        .then(res => {
          for (var i = 0; i < res.data.message.length; i++) {
            const imgurl = `../../static/${res.data.message[i].imgurl}`;
            this.imgurl.push(imgurl);
          }
          // 獲取到圖片後,調用this.imgLoad()方法定義圖片初始高度
          this.imgLoad();
        })
        .catch(error => {
          console.log(error);
        });
    }
  },
  mounted() {
    this.getImgUrl();
    // 監聽窗口變化,使得輪播圖高度自適應圖片高度
    window.addEventListener("resize", () => {
      this.imgHeight = this.$refs.image[0].height;
    });
  }
};
</script>
相關文章
相關標籤/搜索