user12753393
user12753393

Reputation:

Change background depending on data (Vue3)

I am making a weather app but don't understand why my code doesn't change background image.

Codepen of app: https://codepen.io/Link0w0/pen/ZEeBaOj

Code I added to change background:

<div id="app" :class="typeof weather.main != 'undefined' && weather.main.temp > 16 ? 
    'warm' : ''">
  #app.warm {
  background-image: url('https://images.unsplash.com/photo-1581205135021-fbad89f942a6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2894&q=80')
     background-size: cover;
  background-position: bottom;
}

Upvotes: 3

Views: 419

Answers (2)

Sandman
Sandman

Reputation: 402

You have several mistakes in your code on codepen:

  1. Change
<div id="app" :class="typeof weather.main != 'undefined' && weather.main.temp > 16 ? 'warm' : ''">

to

<div id="app" :class="weather.main && weather.main.temp > 16 ? 'warm' : ''">
  1. You have a closing </div> directly afterwards the <div id="app" ... snippet. Move this closing tag after the closing </main> tag.

Here ist a working example with a mocked weather object: https://codepen.io/sandmaan/pen/oNZBbYY

Upvotes: 2

vishwas
vishwas

Reputation: 94

You can replace the :class logic with below code

<div id="app" :class="{warm: weather.main && weather.main.temp > 16}">
    <!-- rest of code -->
</div>

In the CSS part you can replace #app.warm to .warm

  .warm {
    background-image: url('https://images.unsplash.com/photo-1581205135021-fbad89f942a6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2894&q=80')
    background-size: cover;
    background-position: bottom;
  }

Upvotes: 0

Related Questions