marc-leopold/components/BackgroundImageLoader.vue

120 lines
2.0 KiB
Vue

<template>
<div class="background-image-loader">
<div class="background-container">
<div class="background background-default"
:style="backgroundDefaultStyle">
</div>
<transition name="fade">
<div class="background background-img"
:key="loadedImageUrl"
:style="backgroundStyle"
>
</div>
</transition>
</div>
</div>
</template>
<script>
import imageLoader from '~/mixins/imageLoader.js'
export default {
mixins: [ imageLoader ],
props: {
imageUrl: {
type: String,
required: false,
default: function () {
return null
}
},
},
data () {
return {
loadedImageUrl: null,
}
},
computed: {
backgroundDefaultStyle () {
return {
background: 'linear-gradient(310deg, #35405d, #6174aa, #a8b3d0, #e2e5ef)'
}
},
backgroundStyle () {
let style = {}
if (this.loadedImageUrl) {
style.backgroundImage = `url(${this.loadedImageUrl})`
}
return style
}
},
watch: {
imageUrl () {
if (this.imageUrl) {
this.setImage(this.imageUrl)
}
},
},
mounted () {
this.setImage(this.imageUrl)
},
methods: {
setImage(url) {
if (url === null) { return }
this.loadImage(url)
.then(img => {
this.loadedImageUrl = img.src
this.$emit('imageLoaded', img)
})
.catch(err => {
this.$emit('imageLoadError', err)
})
},
},
}
</script>
<style lang="scss" scoped>
.background-image-loader {
position: relative;
width: 100%;
height: 100%;
}
.background {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.background-img {
background-size: cover;
background-position: center center;
opacity: 1;
}
.fade {
&-enter-active {
transition: opacity 2s 1s;
}
&-leave-active {
transition: opacity 3s;
}
&-enter, &-leave-to {
opacity: 0;
}
}
</style>