I'm facing a challenge in setting the background image of my #app element in Vue to the response obtained from Unsplash's API. Although I can fetch the image URL, I'm struggling to apply that information to the background style element.
My main objective is to have a random image displayed on the screen every time the page reloads.
Here's my approach:
- I retrieved the URL from the Unsplash API within the methods section
- Next, I created an image in the data section and assigned it the response containing the URL
- Finally, I tried setting the style attribute in the template section to :style="image"
Unfortunately, this method hasn't been successful for me so far. I considered using computed properties but wasn't sure where to begin.
Furthermore, since there's a linear gradient in the background property, I'm concerned that modifying the image part might remove the linear gradient segment entirely. Any insights or assistance would be greatly appreciated! Thank you
Below is my app.vue file
<template>
<div id="app" :style="image">
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'App',
data() {
return {
image: null,
}
},
methods: {
renderImage: function() {
axios
.get(
'https://api.unsplash.com/photos/random/?client_id=MY_KEY'
)
.then(response => {
console.log([response.data, response.data.location.title])
this.image = response.data.urls.full
})
}
},
mounted: function() {
this.renderImage()
}
}
</script>
<style lang="scss">
#app {
background: linear-gradient(
to bottom,
rgba(245, 246, 252, 0) 45%,
rgb(0, 0, 0) 100%
)
no-repeat center fixed;
background-size: cover;
}
</style>