Search code examples
cssvue.jsconditional-statementsstyles

Vue.js change background-image on multiple conditions


is there a way to change a background-image on conditions?

Im trying to build a weatherapp and I will change the background of a div. Like:

Weather api returns:

  1. rainy -> change background image to rain.jpg
  2. snow -> change background image to snow.jpg
  3. sunny -> change background to sunny.jpg
  4. etc.

I've tried multiple ways already but nothing worked.


Solution

  • <template>
      <div :class="{background_image}"></div>
    </template>
    
    <script>
    export default {
      // ...
      data() {
        return {
            backgroundImage: 'snow'
        },
       computed:{
        background_image : function () {
    
            switch(this.backgroundImage) {
                case 'snow':
                        return 'bg-snow';
                case 'rainy':
                        return 'bg-rainy';
                case 'sunny':
                        return 'bg-sunny';
                default:
                        return 'bg-default';
                }       
        }
      },
      methods: {
        apiCall() {
            //api call update background image according to the response
            this.backgroundImage = response ; // response contains sunny text
            
        }
      },
      // ...
    }
    </script>
    <style>
    
    .bg-sunny{
        background-image: url('sunny.jpg'); 
    }
    
    .bg-snow{
        background-image: url('snow.jpg'); 
    }
    .bg-rainy{
        background-image: url('rainy.jpg'); 
    }
    .bg-default{
        background-image: url('default.jpg'); 
    }
    </style>