Tips for assigning a background image value in Vue by utilizing a URL produced by an API

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:

  1. I retrieved the URL from the Unsplash API within the methods section
  2. Next, I created an image in the data section and assigned it the response containing the URL
  3. 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>

Answer №1

If you refer to the Vue guide, attempt this:

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

data() {
  return {
    image: '',
  }
},
computed: { // will be re-calculated with changes in the image property
  imageStyleObject() {
    return {
      backgroundImage: `url(${this.image})`...
      // add other styles as needed
    }
  }
}

As for the second part of the query, No, there seems to be no impact on the linear gradient.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Toggle the expansion and collapse of content by clicking on the header dynamically

I need to display a set of items in the UI, including a header and a list of items underneath it. I have a parent component that passes this data to a file below, resulting in a parent-child layout. I now want to implement expand/collapse functionality ...

InvalidSyntaxError: Client login cannot be completed due to an unexpected end of input. Please

I encountered an issue while trying to create a bot that sends welcome messages for my friend's server. Despite numerous attempts to troubleshoot the problem within my code, I have been unable to resolve it. Any assistance in solving this error would ...

Retrieving string array elements within a Vue.js v-for iteration

Trying to extract string values from an array within a function. The component declared in the template looks like this: <video-preview v-for="video in playlist" vid-id="how-to-retrieve-string -value-from-the-current-iteration-in-playlist"></vi ...

A JavaScript async function with a nested call inside

Below is my node function for the API server: router.post('/find', async (req, res) => { try { const firewalls = []; let count = 0; const devices = await Device.find({ ...req.body }); devices.forEach(async (item) => { ...

Issues with ellipses not functioning properly have been identified specifically on Safari when using the line

Currently, I am using the line-clamp feature to restrict the titles on a blog to only two lines at most. This functionality works perfectly fine on Firefox and Chrome browsers; however, when it comes to Safari, the ellipsis appears in the middle of the sen ...

Are you searching for a stylish tabbed navigation menu design?

I am searching for a tabbed navigation menu specifically designed to showcase images as the tab items. Here is an example of what I have in mind: <div class="menu"> <a href="#"> <img src="images/Chrysanth ...

AngularJS $log - display line numbers

When using angularjs $log in chrome, it displays the line as: angular.js:9037. I'm looking to have the line number where I actually call this method shown instead. (Displaying my js name and the correct line). Is there a way to achieve this since Angu ...

Optimize flexbox navbar layout by eliminating unnecessary spacing between items

Greetings! As a novice in the world of web development, I must admit that I am facing some difficulties with my homework assignment. Despite my several attempts, I am unable to remove the spacing in the navbar on my university website clone project. It sim ...

Alias destructuring for arrays within nested objects

I'm currently attempting to change the names of certain objects from one array (eventFetch) and transfer them into another array (mapEvents). I initially tried using destructuring aliases for this task, but since I need to rename a nested object, it d ...

Unraveling the Mystery of the JavaScript forEach() Function

Exploring the use of nodejs in Ubuntu and delving into the MDN documentation for the JavaScript forEach() method. While aware of alternative methods, I find that hands-on learning suits me best; my current goal is to create a unique array named copy, conta ...

A guide to declaring functions based on certain conditions

I am looking to assign a function that is the result of a ternary operator, which in turn calls one of two functions. The code snippet I have written so far is as follows: const action1 = (x: number) => { // do something ...

Can the post URL be saved as a unique session name?

I am currently working on a unique homepage background feature for my website. In the HTML code, I have included: <form action="'.$_SERVER['PHP_SELF'].'"> <input type="text" width="128px" name="mybg"> <input type="submit ...

Executing an SQL delete query with a button click using a JavaScript function in PHP

I have created a setup with three essential files - index.html, database.php, and function.js. In database.php, there is a form generated containing a delete button that triggers the deletion SQL query when clicked. The primary objective is to present a ta ...

The $modal popup function does not recognize the scope value as an object when it is undefined

I'm facing an issue with my code that involves using a $uibModal popup to add a new record. Despite passing the scope object into the function to save it, I keep getting 'undefined' as the result. Below is the code snippet along with the [pl ...

Is there an Angular counterpart to Vue's <slot/> feature?

Illustration: Main component: <div> Greetings <slot/>! </div> Subordinate Component: <div> Planet </div> Application component: <Main> <Subordinate/> </Main> Result: Greetings Planet! ...

Leveraging Selenium Web Driver to interact with JavaScript global variables within Jquery

I'm attempting to perform a functional test in Python using Selenium and need to retrieve the value of a global variable in JavaScript that was declared on a specific page. Typically, browser.execute_script("return globalVar;") works as expected. How ...

Tips for emphasizing a chosen hyperlink within a jQuery Mobile panel

I am currently working on a jquery mobile page that includes a navigation menu in a sliding panel. While the functionality is good, I am looking to enhance the user experience by highlighting the selected link in the navigation. Typically, I would utilize ...

Notification triggered in GridView editing according to authorization levels

I have a formview displaying data with an option to edit each row. There are different user roles in my system such as Admin, SuperUser, and User. If a non-Admin user tries to edit a row, I want to display a warning message. Currently, the JavaScript funct ...

Adjusting the position of an image on a webpage as the user scrolls

Looking to add some flair to your website by making an image slide to a specific spot when you scroll? Imagine the page loading with the image sliding elegantly to the left, then as you start scrolling, it smoothly transitions to the center or bottom of th ...

Steps to fill a select dropdown with numbers ranging from 1 to 10, ensuring that each number has a distinct index or value

What is the best way to create a select dropdown containing numbers from 1 to 10, with each option having a distinct value and the default selected option being 1? HTML <select [(ngModel)]="selectNum"> <option value=""> </option& ...