[Vuejs]-How to change background in VueJS per user type

0👍

Your problem is to re-render the component correctly when you change a user. You can add style in a tag in your Vue template. And add :key on this for re-render, smth like that:

  <template>
     <div :style="styleObject" :key="uniqKey">
            // your code
     </div>
   </template>

    <script>
        export default {
          data() {
             return {
               styleObject: {
                 backgroundImage: `url(${require('@/assets/path/to/your/img.jpg')})`   
              },
            uniqKey:0 // change this for re-render
          },
          methods: {
            forceRerender() {
              this.styleObject.backgroundImage = '' //new image 
              this.uniqKey+= 1;  
            }
          }
    }       
    </script>

You can read more about it here.

0👍

Assuming you wish to change the background image of a component, doing so in the template of that component is simple, you can leverage the class property and dynamically change the class base on the userType(which here I am getting from the props but its up to you how you get the user type value, computed property, store, http call etc….)

<template>
  <div :class="userType === 'user' ? 'backgroundUser' : 'backgroundCompany'">
    .....
  </div>
</template>
export default {
  props: {
    userType: {
      type: String,
      required: true
    }
  }
}
<style scoped>
  .backgroundCompany{
  background-color: white;
}

.backgroundUser{
  background: url('/img/bg_img.png') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
    min-height: 100%;
}
</style>

Leave a comment