Customize the background color in VueJS based on user roles

I am currently working on a vuejs project with different user levels.

In the "user" level (and public area), there is a background image, while in the "admin" level, a plain white background is displayed.

I have read that using style tags in the template without the scoped keyword can affect everything. I tried this approach but it did not yield the desired results.

After experimenting by placing the styles in the parent div, everything worked almost perfectly. However, on the logged out page, the image does not cover the entire page, leaving a large white space.

Previously, I had applied the CSS directly to the body within the header component. The snippet of CSS code below shows my attempt at applying it to the parent div:

.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%;
}

During my troubleshooting process, I referred to Stackoverflow posts #49516424 and #48172814 for insights.

UPDATED: I have included a partial screenshot of the issues faced when the styles are applied in App.vue as the style for div id=app. While the admin section displays the pure white background correctly, the user section does not cover the entire body. https://i.sstatic.net/UhkEV.png

Answer №1

If you want to update the background image of a component, you can easily do so within the template of that component. By utilizing the class property and dynamically changing the class based on the userType (which may come from props or other sources like computed properties, stores, or HTTP calls), you can achieve this functionality.

<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>

Answer №2

If you're facing an issue with re-rendering the component correctly when a user is changed, one way to tackle this is by adding styles within a tag in your Vue template and using :key for re-rendering purposes. Here's an example of how you can implement this:

  <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 // modify this value for re-render
          },
          methods: {
            forceRerender() {
              this.styleObject.backgroundImage = '' // new image 
              this.uniqKey+= 1;  
            }
          }
    }       
    </script>

To learn more about this technique, you can visit this resource.

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

Tips for implementing the JSON object table filter functionality

My website features a collection of json objects organized as shown below: [ { "a": true or false, "b": "information", "c": "information", "d": "information", "e": "information" }, ... ] The goal here ...

Retrieve information from a MySQL database and integrate it into a different application

This php script is used to generate a table with a "book" button next to each row. The goal is to extract the values of "phase" and "site" from the specific row where the "book" button is clicked, and transfer them to another form (in "restricted.php") fo ...

Next.JS - What is the reason behind data fetching occurring on both the server and client side?

When I call a regular fetch function in the index.js component and then log the response to the console, something unexpected happens. Despite the fetch being inside the component function, the response is also logged on the server side: it shows up in the ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

AngularJS Alert Timer Setting

Is there a way to display the timer value in AngularJS? I have included the following code for the timer tag: <timer interval="1000" countdown="100">{{countdown}}</timer> I have also added an alert function in the script.js file to display th ...

Using JavaScript to call an API in PHP and determine how to handle a response that is not equal to 200 by printing an

Greetings! I am aiming for a scenario where, upon clicking the link, the user's parameter is transferred to JavaScript. This parameter will then be used in ajax to trigger a call to my PHP file containing the API. The API, after processing the parame ...

The DOM is failing to refresh in Vue.js even after the array has been updated

After receiving a list of items using AJAX, I store them in a data Array: loadSparepartFiles: function() { var vm = this; vm.activeSparepart.attachments = []; ajaxApi.loadJson('spareparts/sparepart/getFiles/'+vm.activeSparepartId, fu ...

I possess 9 captivating visuals that gracefully unveil their larger counterparts upon being clicked. Curiously, this enchanting feature seems to encounter a perplexing issue within the realm of web browsing

<style type="text/javascript" src="jquery-1.11.0.min.js"></style> <style type="text/javascript" src="myCode.js"></style> </body> //jquery is within my site directory on my desktop $(document).ready(function(){ //note: $("#ar ...

What are some ways I can make my content come alive on my website using the Tympanus examples

After spending hours searching for a way to add animation to my content, I finally found a technique that seemed promising. Despite following the same steps as outlined in the tutorial I found, I was disappointed to discover that there was no animation o ...

Obtain the text from an altered stylesheet in Firefox

I am currently programmatically updating stylesheets for a web page using JavaScript. My method involves having a local copy of the page and all associated assets stored on a server. After I finish making changes to the stylesheets, my goal is to save the ...

How to utilize a parent variable in Vue.js?

Within my Vue Component, I am incorporating Dropzone.js. Rather than utilizing vue2-dropzone, as it cannot be attached to the body, I have created a custom setup. Here is an overview of my component: export default { props: [ 'maxsize&apo ...

Scrolling will only function properly on this page if you refresh it

I have a setup where buttons on my first page lead to specific elements on the second page. To achieve this, I pass the element IDs in the URL like so: mysite.com/secondpage/:promo1(/2/3, depending on the button clicked.) Upon landing on the second page, ...

Tips for using a JavaScript function to navigate to a specific division (<div>) on an HTML page

I am facing an issue where I need to redirect within the same HTML page that includes a add-form div. What I want is that when I click on a button, my redirection should be to a specific div containing some code. Currently, I have code that redirects to a ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

Creating an interactive Table of Contents in Sharepoint using only JavaScript

Imagine you have a massive Sharepoint wiki page filled with various heading tags like H1, H2, H3, and H4 - now picture creating a dynamic Table of Contents using these tags. The goal is to categorize these tags by group and utilize the HTML <detail> ...

Unsuccessful execution of JavaScript in returned HTML after being appended with jQuery .load() or .ajax()

I have attempted to use .load() and $.ajax in order to retrieve some HTML that needs to be added to a specific container. However, the JavaScript enclosed within the fetched HTML is not executing when I add it to an element. When employing .load(): $(&ap ...

Guidance on creating a custom color selection tool for a specific task

Looking for assistance in converting a code snippet that uses <button> elements to select colors into a color picker. I am unsure how to retrieve the selected color and use it within a JavaScript function. Can someone provide guidance on this? Here i ...

Tips on transforming a JavaScript function constructor into TypeScript

Transitioning from JavaScript to TypeScript has presented me with some challenges. One of the tasks I need to accomplish is converting a constructor function into its TypeScript equivalent. The original JavaScript function looks like this: export default ...

Working with ReactJS, Material-UI, and Javascript: Facing challenges in applying rounded borders to TableRow components

I've been trying to achieve rounded borders on a TableRow element, but adding the style "borderRadius: 5" doesn't seem to have any effect. When I try wrapping the TableRow in a Box element with borderRadius, it does make the borders rounded but m ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...