效果:
页面:
<div class="wrapcss" :style="{ height: scrollerHeight }">
<img :src="bgimg"/>
</div>
script部分:
data () {
return {
bgimg: require("../assets/image/Top3.jpg"),
screenWidth: document.body.clientWidth, //头部轮播图比例
}
}
watch: {
screenWidth(val) {
// 为了避免频繁触发resize函数导致页面卡顿,使用定时器
if (!this.timer) {
// 一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
this.screenWidth = val
this.timer = true
let that = this
setTimeout(function() {
// 打印screenWidth变化的值
console.log(that.screenWidth)
that.timer = false
}, 400)
}
}
},
computed: {
scrollerHeight() {
return this.screenWidth / 3.22 + 'px'
},
},
mounted() {
var _this = this
window.onresize = () => {
return (() => {
window.screenWidth = document.body.clientWidth
_this.screenWidth = window.screenWidth
})
}
}
css:
.wrapcss {
width: 100%;
height: auto;
}
.wrapcss img {
width: 100%;
height: 100%;
object-fit: cover;
}