LeagueStats/client/src/components/LazyBackgroundImage.vue

75 lines
1.3 KiB
Vue
Raw Normal View History

2019-08-19 12:49:20 +00:00
<template>
<transition :name="transitionName">
<div
v-show="imageState === 'loaded'"
:class="[imageClass, imageState]"
:style="computedStyle"
:data-state="imageState"
></div>
</transition>
</template>
<script>
export default {
props: {
imageSource: {
type: String,
required: true
},
imageClass: {
type: String,
required: false,
default: ''
},
backgroundSize: {
type: String,
required: false,
default: 'cover'
},
moreBackgrounds: {
type: String,
required: false,
default: ''
},
2019-08-19 12:49:20 +00:00
transitionName: {
type: String,
required: false,
default: ''
}
},
data () {
return {
imageState: 'loading',
asyncImage: new Image()
}
},
computed: {
computedStyle () {
if (this.imageState === 'loaded') {
return `background-image: ${this.moreBackgrounds} url(${this.asyncImage.src}); background-size: ${this.backgroundSize}`
2019-08-19 12:49:20 +00:00
}
2019-08-23 14:48:16 +00:00
return ''
2019-08-19 12:49:20 +00:00
}
},
2019-08-23 14:48:16 +00:00
mounted () {
this.$nextTick(() => {
this.fetchImage()
})
},
2019-08-19 12:49:20 +00:00
methods: {
fetchImage () {
this.asyncImage.onload = this.imageOnLoad
this.imageState = 'loading'
this.asyncImage.src = this.imageSource
},
imageOnLoad () {
this.imageState = 'loaded'
}
}
}
</script>