在使用绑定样式的功能时,发现对div的backgroundSize属性设置不起作用,于是只能 使用一个比较笨拙的办法,解决这个问题
初始加载是生效的,但是之后当点击按钮改变图片地址后,无法填充背景图片
改变背景之后
第一个使用的是计算属性,绑定style,使用background-size和backgSize都无效
下面的是使用原生js设置样式
第一个
<template>
<div>
<div class="img" :style="style"></div>
<button @click="prev">prev</button>
<button @click="next">next</button>
</div>
</template>
<script>
export default {
name: "swiper",
data() {
return {
cur_index: 0,
imgs: [
'https://i1.mifile.cn/a4/xmad_15195327867488_jlLnp.jpg',
'https://i1.mifile.cn/a4/xmad_15185161540821_qPMoX.jpg',
'https://i1.mifile.cn/a4/xmad_15193829171444_CQnuo.jpg',
'https://i1.mifile.cn/a4/xmad_15192945916761_ormJz.jpg',
],
}
},
computed: {
style() {
return {
background: `url('${this.imgs[this.cur_index]}') no-repeat`,
'backgroundSize': 'contain'
}
}
},
methods: {
prev() {
this.cur_index = (this.cur_index + this.imgs.length - 1) % this.imgs.length
},
next() {
this.cur_index = (this.cur_index + 1) % this.imgs.length
}
}
}
</script>
<style scoped>
.img {
width: 400px;
height: 300px;
border: 1px solid black;
}
</style>
第二个
<template>
<div>
<div class="img" :style="style" ref="swiper"></div>
<button @click="prev">prev</button>
<button @click="next">next</button>
</div>
</template>
<script>
export default {
name: "swiper",
data() {
return {
cur_index: 0,
imgs: [
'https://i1.mifile.cn/a4/xmad_15195327867488_jlLnp.jpg',
'https://i1.mifile.cn/a4/xmad_15185161540821_qPMoX.jpg',
'https://i1.mifile.cn/a4/xmad_15193829171444_CQnuo.jpg',
'https://i1.mifile.cn/a4/xmad_15192945916761_ormJz.jpg',
],
}
},
watch: {
cur_index() {
this.refresh()
}
},
methods: {
refresh() {
this.$refs.swiper.style.background = `url('${this.imgs[this.cur_index]}') no-repeat`
this.$refs.swiper.style.backgroundSize = 'contain'
},
prev() {
this.cur_index = (this.cur_index + this.imgs.length - 1) % this.imgs.length
},
next() {
this.cur_index = (this.cur_index + 1) % this.imgs.length
}
},
mounted() {
this.refresh()
}
}
</script>
<style scoped>
.img {
width: 400px;
height: 300px;
border: 1px solid black;
/*background-size: contain;*/
}
</style>