When using the function of binding style, I found that setting the backgroundSize property of div does not work, so I can only use a clumsy method to solve this problem
The initial loading is valid, but after clicking the button to change the image address, the background image cannot be filled
after changing the background
The first one is using computed properties, binding style, using background-size and backgSize are invalid
The following is to use native js to set the style
First
<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>
the second
<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>