解决方法
总结:当要改变某一个数值时考虑他在生命周期中的阶段,看他是要在渲染之前,还是之后,并且要记录数值。
vue的生命周期中拥有一个mounted属性
是在页面渲染完成后的状态,通过该状态响应式的改变在走马灯的高度
代码如下
<template>
<div class="block">
<!----通过bannerHeight来修改轮播图的高度>
<el-carousel trigger="click" :height="bannerHeight">
<el-carousel-item v-for="item in banners">
<a :href="item.link">
<img :src="item.image" alt="">
</a>
</el-carousel-item>
</el-carousel>
</div>
</template>
<script>
export default {
name: "Carousel",
props:{
banners:{
type:Array,
default(){
return []
}
},
},
data(){
return{
bannerHeight:'150px',
screen:'0px'
}
},
<!----声明改变高度的方法,因为在mounted中不建议使用数值计算-->
methods:{
getSize(){
if(this.screen > 480){
this.bannerHeight = 300 + 'px'
}else{
this.bannerHeight = 150 + 'px'
}
}
},
mounted() {
<!--首次进入页面时需要记录当前的数值,不然刷新的时候会按照初始化的数值进行样式的绑定-->
this.screen = window.innerWidth
this.getSize()
<!--监听窗体大小的变化-->
window.onresize = () => {
this.screen = window.innerWidth
this.getSize()
}
}
}
</script>
<style scoped>
.el-carousel__item img {
width: 100%;
height: 100%;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>