哈哈,久違了各位。我又回來了,最近在做畢設,所以難免會遇到很多問題,需要解決很多問題,在萬能的博友幫助下,終於解決了Element-ui中輪播圖的圖片高度問題,話不多說上代碼。
那個axios的使用不重要,大致思路就是頁面渲染前拿到當前窗口的寬度*圖片比例給輪播圖一個初始的高度,當窗后大小發生變化時,監聽事件里將輪播圖高度重新賦值即可,再次感謝兩位博友的幫助
<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>
