How to set the value of a background Image in Vue using a URL generated by an API

Tags: , , , ,



I am trying to set the value of the background image of my #app element in Vue to the response that is generated from Unsplash’s API. I am able to retrieve the image URL, but I am having some difficulty in trying to relay that information to the background style element.

Overall, my goal is to use a random image and display it on the screen every page reload.

My method:

  1. I pulled down the URL from the Unsplash API in the methods section
  2. I then created an image in the data section and set that equal to the response containing the URL
  3. Finally, I set the style attribute in the template section to :style=”image”

This has not been working for me. I thought of using computed properties, but I wasn’t even sure where to start there.

Additionally, since I have a linear gradient on the background property, would altering the image part effectively delete the linear gradient part on the background property?

If you can provide any assistance that would be greatly appreciated! Thanks

Below, I have provided 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>

Answer

Following the syntax in the Vue documentation, try this

<template>
 ....
  <div id="app" :style="imageStyleObject">
....
</template>

data() {
  return {
    image: '',
  }
},
computed: { // will be re-computed when the image property changes
  imageStyleObject() {
    return {
      backgroundImage: `url(${this.image})`...
      // insert other styles
    }
  }

}

Regarding the second part of the question, No, I see no reason why the linear gradient should be affected.



Source: stackoverflow