Adjust the Vue.js background color according to a specified class name

Just starting out with vue.js and exploring the possibilities. I have a scenario where I need to dynamically change the background color based on a class name in vue. Is there a way to achieve this without relying solely on CSS? Ideally, I would like to simply update the class name in the HTML markup and have the associated background color render automatically.

HTML:

<div class="page-header__container" :style="{ background: color }">
    <div class="container">
      <div class="row">
        <div class="page-header">
          <h1 class="page-header__text">
            Page Header Lorem ipsUm
          </h1>
</div>

js:

export default {
   name: 'Header',
   data() {
   return {
   color: '#333'
    };
   }
 };

css:

bg-one{
background-color: #673AB7
}
bg-two{
background-color: #7293A0
}
bg-three{
background-color: #45B69C
}

Answer №1

Check out this code on JSFiddle: https://jsfiddle.net/kyz19b7r/

Creating a new Vue instance:
new Vue({
  el: "#app",
  data: {
    bgColour: 'blue',
    classes: [ 'blue', 'red', 'green' ]
  }
})
CSS styling for the app:
body {
  background: #fff;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

.blue {
  background: blue;
}

.red {
  background: red;
}

.green {
  background: green;
}
Vue template:
<div id="app" :class="bgColour">
  <select v-model="bgColour">
    <option v-for="myClass in classes" :value="myClass">{{ myClass }}</option>
  </select>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

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

Integrating AngularJS code into dynamically generated HTML using JavaScript

I am currently utilizing an outdated version of AngularJS (1.3). I have a page where I need to dynamically display different content based on database values. If the user interacts with the page and changes the database value, I want the displayed content ...

Animate or resize with a focal point

Seeking suggestions on how to create an animation effect for changing the width and height of a div from the top center. I experimented with using effect('scale'), but it reverts back after completion due to being based on show/hide actions. I t ...

Top recommendations for implementing private/authentication routes in NextJS 13

When working with routes affected by a user's authentication status in NextJS 13, what is the most effective approach? I have two specific scenarios that I'm unsure about implementing: What is the best method for redirecting an unauthenticated ...

Is there a way to verify the location of an element?

Currently, I am attempting to monitor the position of the 'car'. When the car reaches a top offset of 200px, I would like to apply a specific property to the 'phone' element. The concept is that as you scroll down, the car will move, an ...

Having trouble with the DataTables jQuery plugin? Seeing a blank page instead of the expected results?

I've been trying to set up the Datatables jquery plugin for my HTML table but it's not working as expected. I have linked to the Datatables CDN for CSS styling and script, along with Google's hosted jQuery plugin. Additionally, I have a loca ...

Transmitting information after a delay when using ng-keyup in AngularJS

In my Angular app, I am using ng-keyup to search data from my backend. However, the issue is that it sends a request to the server with every key press. Is there a way to configure it to send a post request only after the user has paused or stopped typing? ...

Tips for fixing the error "Unhandled error: state.set is not a function"

My code is utilizing immutable.js in the reducer, but I keep encountering an error stating 'state.set is not a function'. Interestingly, when I modify the code to exclude immutable, the error disappears. import React from 'react'; impo ...

How to implement a Typescript interface without necessarily implementing the parent interfaces

Within my current project, I have defined the following interfaces: interface foo { fooProperty: number; fooFunction(): void; } interface bar extends foo { barProperty: string; barFunction(): void; } Now, I am interested in creating a class like ...

Kendo dropdown list won't trigger the change() event

I am using a Kendo DropDownList to load data from JSON. However, the onchange event of the dropdownlist is not firing. <input class="ddEmailInitiation" /> <script>$(".ddEmailInitiation").kendoDropDownList ({ dataTextField: "Type", dataSour ...

Is it possible to manipulate divs with CSS media queries for positioning?

I currently have a footer displayed on the desktop version of my website, which appears like this: https://i.sstatic.net/ZMUZj.png However, for tablets (with a width less than or equal to 960px), I need to adjust the layout using media queries to look li ...

Encountering a CORS Policy Blockage when Making a POST Request with Spring Boot

Exploring the realm of Spring Boot, I ventured into creating an endpoint from scratch. As a newcomer to Spring Boot, things seemed to be going smoothly until I attempted to call the endpoint using POSTMAN for testing purposes (running through the complete ...

Guide to using vite-plugin-rewrite-all in conjunction with Quasar for Vue 3 - or alternative method to enable periods in paths

Encountering a 404 error when using quasar+vite in vueRouterMode: 'history' mode with paths containing a period/dot in the id? This issue has been discussed in various places: https://github.com/vitejs/vite/issues/2415 https://github.com/vitejs/ ...

Is there a way to format this into four columns within a single row while ensuring it is responsive?

I am working on a layout with a Grid and Card, aiming to have 4 columns in one row. However, the 4th column ends up in the 2nd row instead, as shown below: https://i.sstatic.net/gOeMm.png My goal is to align all 4 columns in a single row. Additionally, w ...

Basic title in material-ui navigation bar

I was hoping to display a simple label on the right side of the AppBar. Currently, I am using the iconElementRight prop and inserting a disabled flat button: <AppBar iconElementRight={<FlatButton label="My Label" disabled={true}/>} /> Thi ...

One-of-a-kind Version: "Utilizing CSS to Capitalize an

Imagine having the following strings. i and we. me and you. he and she. Is it possible to achieve the desired result using PURE CSS? I and We. Me and You. He and She. If capitalizing the text using text-transform: capitalize is used, it will yi ...

Exploring the distinction between type-based and value-based props validation in VueJS

defineProps({ lastName: { type: String, required: true }, }); const props = defineProps({ lastName: String }) I have a simple question regarding the code snippets above. The first block of code defines an object and adds appropriate validat ...

Website errors appear on the hosted page in <body> section without being present in the code

Hello there, I have set up a debug website using my "Olimex ESP-32 POE" to send internal data via JSON, eliminating the need for Serial Output from the Arduino IDE (the reasons behind this are not relevant). #include "Arduino.h" #include <WiF ...

Tips for achieving compatibility between systemjs module loading and .net mvc architecture

Upon finding the ng-book 2, I saw it as a promising resource to delve into Angular 2. Although I am new to module loaders and have minimal experience with npm and node, I find the terminology and assumed knowledge to be quite perplexing. I decided to use ...

Problem with BeautifulSoup table parsing

I've been trying to create a table with expenses, amounts, and actions, but I'm having trouble with the alignment. I attempted to adjust it by changing the width, but that didn't solve the issue. Can someone point out what I'm doing wro ...

What could be causing my body to resist adapting to the information on this website?

Is there a way to adjust content for a page using an overlay grid without exceeding the body boundaries? I'm facing this issue and struggling to find a solution. I've attempted to make a body reference in CSS and adjust the height, but no progres ...