Customizing Page Backgrounds in Vue: A Guide to Changing Colors

Here is the Vue.js code I have. I want to change the background color for each page individually, but currently, I have to go to App.vue and change it there, affecting all pages because the main container that includes all pages is App.vue. Is there a way to change the background color for only one page? Thank you in advance.

<template>
<b-container>
<h1> Ask Question </h1>
<br>
 <br />
<b-row align-v="center">
<b-col cols="8">

    <b-form-group

  
 @submit="postData" method="post">
      <b-form-input
        type="text"
        name="title"
        v-model="posts.title"
        placeholder="Title"
        required
     
      <b-form-input id="question-input"
        type="text"
        name="question"
        v-model="posts.question"
        placeholder="Question"
        required
      /><br /><br />
    
      <b-button class="primary" type="submit">Post</b-button>
    </b-form-group
>
  
</b-col>

</b-row>



 </b-container>
</template>

<script>
export default {
  name: "postComponent",
  data() {
    return {
      posts: {
        title: null,
        question: null,
      },
    };
  },
  methods: {
    postData(e) {
        this.axios.post("",this.posts).then(( result) => {
console.log(result)
        })
        // console.warn(this.posts)
      e.preventDefault();
    },
  },
};
</script>
<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Cairo&displa');
.container{
    padding:50px;
    font-family: 'Cairo', sans-serif;
}
#question-input{
    padding: 35px 10px 90px;
}


</style>

App.vue

<template>


<div class="app">
<Header />
<router-view />
</div>

</template>

<script>
import Header from './components/Header';

export default {
  name: 'App',

  components: {
    Header,
  },

  data: () => ({
    //
  }),
};

</script>
<style>
.app{
  width: auto;

}
</style>

Answer №1

To customize the background color of a component, you can add a specific class in the scoped style section:

<template>
  <main class="crypto_bg">
    ...
  </main>
</template>

<style scoped>
 .crypto_bg {
   background: #1d2444;
 }
</style>

In my project, I have two pages: crypto and stock, which are controlled by a toggler in the Header.vue. The stock page serves as the default page, while the crypto page has a unique design with different backgrounds for header and body.

App.vue:

<template>
  <div id="app">
    <Header @stock="showStockPlatform" @crypto="showCryptoPlatform" />

    <Main v-if="stockMainShown" />

    <CryptoMain v-if="cryptoMainShown" />

    <router-view />
  </div>
</template>

<script>
  data() {
    return {
        stockMainShown: true,
        cryptoMainShown: false,
    };
  },
  methods: {
    showStockPlatform: function (platform) {
        this.stockMainShown = platform;
    },

    showCryptoPlatform: function (platform) {
        this.cryptoMainShown = platform;
    },
  },
</script>

To toggle between these pages/components in Header.vue, emit an event to update App.vue and set variables accordingly:

<script>
 export default {
  data() {
    return {
        stockPlat: true,
    };
  },
  methods: {
    showPlatform(platform) {
        if (platform.toLowerCase() == "stocks") {

            this.$emit("stock", true);
            this.$emit("crypto", false);

            this.stockPlat = true;
        } else if (platform.toLowerCase() == "crypto") {

            this.$emit("stock", false);
            this.$emit("crypto", true);

            this.stockPlat = !this.stockPlat;
        }
    },
  },
 };
</script>

In the Template tag of Header.vue, adjust the background color based on the current page being displayed:

<template>
  <div :class="[stockPlat ? 'bgDark' : 'bgBlue']">
    ...
  </div>
</template>

In the Style tag, define the styles for the different backgrounds:

<style>
  .bgDark {
    background-color: black;
  }
  .bgBlue {
    background-color: blue;
  }
</style>

References: https://v2.vuejs.org/v2/guide/class-and-style.html https://v2.vuejs.org/v2/guide/components-custom-events.html

Answer №2

document.body.style.backgroundColor = "<choose your color>";

I'm pretty sure that you can use the document object within any of your Vue methods.

Answer №3

If you want to customize the background color, simply add the following CSS code:

.backgroundcolor {
  background-color: lightblue;
}

You can change the color value in background-color to your desired background color. Don't forget to apply the class "backgroundcolor" to the HTML element where you want to change the background color; for example, you can use it with the <body> tag or something similar. It's unusual to use a class attribute in the <html> tag.

For more information on CSS backgrounds, visit https://www.w3schools.com/css/css_background.asp. If you're looking for coding tutorials in various languages, check out https://www.w3schools.com.

You might also find these resources helpful: https://codepen.io/alemesa/pen/YNrBqr and How to change style of background color using Vue.js only. Give them a try.

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

The PHP SDK function works flawlessly in the local host environment and in console, however, it fails to perform on the browser when deployed

My PHP function is behaving differently between the server's command line and the web page, with successful execution on a local WAMP host. Any thoughts on what could be causing this inconsistency? function getCFTemplateSummary($CFUrl){ //init client ...

What is the best way for my partial components to interact with the main data object in Vue?

Currently, I am utilizing Vue Router to route external .vue files and link them with webpack. In my main.js file, I have an object that sets up my Vue instance. var vm = new Vue({ el: '#app', router, //render: h => h(App), data:{ ...

Displaying a popover upon page load using JavaScript

Currently, I am attempting to implement a JavaScript function that displays a popup on my webpage whenever a user visits the site. The script that I have found uses jQuery, but I am wondering if it is possible to achieve the same result using pure JavaScri ...

The CSS styling for the jQuery UI autocomplete feature is not showing up as expected

Attempting to integrate jQuery UI's autocomplete feature, but encountering issues with the CSS not being applied. 1) College list appears unstyled like a standard ul. 2) Unwanted message "11 results are available, use up and down arrow keys to nav ...

WordPress: Issue with Dropdown onchange Event Not Triggering

I'm having trouble getting an event to fire when the dropdown value changes. Can anyone help me figure out where I might be going wrong? JavaScript code jQuery(document).ready(function($){ jQuery('#_ccounts select').on('change&apo ...

Deciphering the outcome of the splice method in CoffeeScript

Recently, I have been utilizing CoffeeScript in conjunction with the JS splice function. From my understanding, the JS splice function should return the objects that were spliced out and modify the original array. While this concept works smoothly with sim ...

Is it normal for my sweelart2 to consistently be positioned behind my v-dialog component in Vuetify 3?

Why does my sweetalert2 always appear behind my v-dialog in Vuetify3? Can anyone assist me with resolving this issue? I have tried various alternatives for sweetalert2 but have not found a solution yet. Whenever I use sweetalert with v-dialog, the sweetal ...

I'm having trouble with two JavaScript functions interacting - the second one seems to be interfering with the first. How can

I'm facing an issue with my webpage that includes two distinct features: 1) A button that changes feelings on hover, similar to Google's "I'm Feeling Lucky" button 2) An automatic word cloud generation on page load Oddly, the button funct ...

Real estate for a targeted audience

1. Overview I have a list of selectors that should always apply certain properties. Some selectors require additional properties to be added. I'm struggling to find a way to achieve this without repeating code. 2. Minimal CSS Example (MCVE) 2.1 ...

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...

Encountering an 'undefined' error when rendering data in Vue.js

For some reason, I am facing an issue with rendering data stored in a JSON object. It seems to work perfectly fine when written in plain JavaScript, but when I convert it to Vue, it fails to work. I even tried reverting back to an older commit to see if th ...

What is the method to ensure that the Node REPL solely displays the result?

Is there a way to execute a script in Electron that only logs the output value without displaying all the code? I am utilizing xterm.js and node-pty for this project. For instance, consider the following sample code: // Add your code here function multi ...

Using Three.js to load a JSON model and easily implement it in multiple instances

Is there a way to load a JSON model just once and then add it multiple times to the scene with different scales, positions, etc? I've tried adding the Object3D() to an array, assigning a position and scale to each object in the array, adding them to ...

Having trouble updating an array in a mongoose document?

Need help with updating an array in a document by adding or replacing objects based on certain conditions? It seems like only the $set parameter is working for you. Here's a look at my mongoose schema: var cartSchema = mongoose.Schema({ mail: Stri ...

Ways to align list items in the middle of a webpage with CSS

Currently, I am working on a website and looking to create a customized list where the pictures act as clickable links. You can check out the website here. My goal is to have the links adjust to align left based on the browser size, and also have the imag ...

Can you please provide instructions on how to expand the view in the title bar for a JavaScript/CSS/HTML UPW project?

Struggling to integrate the title bar in a UWP project using JavaScript/CSS/HTML and having trouble accessing the necessary APIs. Came across a custom helper class written in c++ in UWP samples on Github, but unable to reference it in my javascript code. H ...

What is the best way to completely eliminate a many-to-many relationship with a custom property?

I have encountered a situation where I am utilizing an entity setup similar to the one explained in this resource. The problem arises when I try to remove entries from post.postToCategories. Instead of deleting the entire row, TypeORM sets one side of the ...

Navigating through the webpage using CSS gradient backdrop

Check out this page. Under the "Pedidos" section, there is a scrolling area with a gradient background. The issue I'm facing is that I want the background to continue scrolling and repeating as I scroll down the page, but it remains fixed. I tried the ...

What could be causing a template value in my AngularJS/Ionic Framework code to not be replaced properly?

Recently, I've been exploring the world of Ionic Framework with Angular by my side. However, I've hit a bit of a roadblock. My goal is to set up tabs at the bottom of my application using a model definition. Here's what I've tried so ...

Issue with Bootstrap dropdown-menu alignment when image_tag contains the "center-block" class

<ul class="logo"> <li class="navtabs dropdown"> <a class="dropdown-toggle" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> <%= image_tag('Thumbnailimagestufffurr ...