Guide on Applying a Dynamic Color in VueJs 3 Composition API/Vuetify Using CSS

Currently, my project utilizes Vue 3 with the composition API and Vuetify for the UI.

I am looking to utilize a color that is already defined in a Vuetify theme variable within my CSS, similar to how I have done it previously in JavaScript.

Although I attempted using CSS var(), it was not successful in achieving the desired outcome.

For more specific details, please refer below this message.

Thank you!

Hello! Below is the template I am working with:

<template>
  <div class="container">
    <div class="mx-auto">
      <div class="demo-app-sidebar-section">
        <b>Total Events ({{ calendarEvents?.length }})</b>
        <!-- create a small colored cube here -->
        <ul>
          <li>
            <b
              >Registered Events
              <span class="legend registered"></span> <!-- issue here --->
            </b>
          </li>
          <li>
            <b
              >Non-registered Events<span class="legend nonRegistered"></span> <!-- problem here --->
            </b>
          </li>
        </ul>
      </div>
    </div>

    <div class="mx-auto">
      <FullCalendar class="demo-app-calendar" :options="calendarOptions">
        <template #eventContent="arg">
          <b>{{ arg.timeText }}</b>
          <i>{{ arg.event.title }}</i>
        </template>
      </FullCalendar>
    </div>
  </div>
</template>

Below are the CSS classes used:

.legend {
  width: 1em;
  height: 1em;
  display: inline-block;
  margin-left: 0.5em;
}

.legend.registered {
  background-color: #03dac6; /*issue here*/
}
.legend.nonRegistered {
  background-color: #e95196; /*problem here*/
}

In another file, the theme is set as follows:

const themeLight: ThemeDefinition = {
  dark: false,
  colors: {
    background: "#F2F0F1",
    surface: "#FFFFFF",
    primary: "#E95196",
    "primary-darken-1": "#3700B3",
    secondary: "#03DAC6",
    "secondary-darken-1": "#018786",
    error: "#B00020",
    info: "#2196F3",
    success: "#4CAF50",
    warning: "#FDBB37",
  },
};

// Dark theme definition
const themeDark: ThemeDefinition = {
  dark: true,
  colors: {
    background: "#121212",
    surface: "#212121",
    primary: "#6B89C9",
    "primary-darken-1": "#3700B3",
    secondary: "#03DAC6",
    "secondary-darken-1": "#018786",
    error: "#B00020",
    info: "#2196F3",
    success: "#4CAF50",
    warning: "#FDBB37",
  },
};

How can I use

vuetify.theme.current.value.colors.secondary,
like this:

const calendarEvents = eventResult.map((event) => {
  let isInscrit = ref(
    event.users?.find((userV) => userV.email === user?.value?.email) !==
      undefined
  );

  if (isInscrit.value) {
    return {
      id: event.id,
      title: event.name,
      start: event.date,
      backgroundColor: vuetify.theme.current.value.colors.secondary, // Set green background for registered users
    };
  } else {
    return {
      id: event.id,
      title: event.name,
      start: event.date,
      backgroundColor: vuetify.theme.current.value.colors.primary, // Set pink background for non-registered users
    };
  }
});

However, in terms of CSS, how can I achieve this?

Thank you!

Answer №1

The Vuetify color options can be accessed through CSS variables, with a naming convention of --v-theme-, such as --v-theme-primary and --v-theme-secondary. These variables contain RGB values, so they should be enclosed in rgb() when used to define colors:

  background: rgb(var(--v-theme-primary));

Vue.createApp({}).use(Vuetify.createVuetify()).mount('#app')
.vuetifyPrimary{
  background: rgb(var(--v-theme-primary));
}

.vuetifySecondary{
  background: rgb(var(--v-theme-secondary));
}
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/vuetify@3/dist/vuetify.min.css" />
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b3babba195e0fbad">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <div class="vuetifyPrimary">has primary background</div>
      <div class="vuetifySecondary">has secondary background</div>
    </v-main>
  </v-app>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@3/dist/vuetify.min.js"></script>

To simplify setting text and background colors, utilize the predefined CSS classes from Vuetify like text-primary or bg-primary.

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

Navigating through a Collection of Pictures using Mouse Movement and Left-click Button

Trying to create a customized PACS viewer for scrolling through a series of CT head images. However, encountering an issue with scrolling through all 59 images. Currently, able to scroll from the first to the 59th image, but struggling to loop back to the ...

What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions: The denominator remains constant The numerator must be unique and fall within the range of 1 to three times the denominator The fraction should not be reducible (e.g., 2/6 ...

Typescript's intriguing concept of objects containing arrays inside other objects

I have a structure similar to this and I am trying to create definitions for types/interfaces, but I am facing issues in making it work correctly. layoutsSet: { 1: { "lg": [ { i: "1", x: 0, ...

Is it feasible to access a service instance within a parameter decorator in nest.js?

I am looking to replicate the functionality of Spring framework in nest.js with a similar code snippet like this: @Controller('/test') class TestController { @Get() get(@Principal() principal: Principal) { } } After spending countless ho ...

Refining types in a series of statements

I'm attempting to merge a series of assertions in a safe manner without the need to individually call each one. For instance, consider the following code: type Base = { id: string, name?: string, age?: number }; type WithName = { name: string }; type ...

CSS: Handling Background Images Responsively

I'm experiencing an unusual issue where the image is not appearing, even though the div box shows up when I highlight elements on the page. Validation and inspection also show no issues. Here is the code: <div class="mainImage"></div> A ...

Customizing the date-select widths: A step-by-step guide

I've been struggling with adjusting the width of different instances of this line: <%= f.date_select :deadline, :order => [:month, :day, :year], class: 'date-pick', id: 'goal' %> Despite creating unique ids for select, d ...

Remove Vue Component from the styling of current application

We integrated a Vue component (using Vuetify) into our existing .NET MVC application. The issue we are facing is that the Vue component is inheriting all the CSS styles from the rest of the application. Here's a simplified version of the HTML structur ...

Is it possible to efficiently structure intricate JSON data onto interfaces in TypeScript with the incorporation of observables?

I am currently working on creating a simple web news reader that relies heavily on the Google News API (). I have set up all the necessary services, models, etc. However, I am having difficulty mapping the data onto specific interfaces. The Google API retu ...

Challenge with CSS Box Shadow

Hey there, I've been attempting to add a shadow effect to a box inside another box but I'm struggling to achieve the desired outcome. <div class="box effect2"> <div class="box effect2"> Box inside a box <div> &l ...

How come TypeScript tuples support the array.push method?

In the TypeScript code snippet below, I have specified the role to be of Tuple type, meaning only 2 values of a specified type should be allowed in the role array. Despite this, I am still able to push a new item into the array. Why is the TS compiler not ...

How can I create two buttons on one line in a Struts2 form?

My form has two buttons - one for registering and the other for canceling the form. I created them using the following code: <s:submit name="cancel" key="project.button.cancel" /> <s:submit name="login" key="form.register.registerBtn" /> How ...

How to use CSS to dynamically adjust the maximum width of an overflow container based on its children's content

I have a container with an overflowing <div> that displays multiple <ul> <li> lists. Each list always contains the same number of bordered <li> items, resembling a table. However, there may be instances where a <ul> has only ...

Changing the button class during an event in Angular 4

In the process of creating an MCQ test, I am looking to implement a feature where selected button options are highlighted in green upon clicking. While I have successfully implemented this feature using Angular 1, I am facing challenges in converting it to ...

Utilizing d3 Charts in Angular 4 Framework

I need assistance with integrating a bar chart in an Angular 4 project, which includes HTML and TypeScript files as components. Can someone please provide guidance on this? The bar chart should show the increase in the number of employees each month, star ...

The v-for directive is unable to access the prop data

<template> <span> <i class="fa fa-star text-warning fa-2x" v-for="r in rating" :key="r"></i> <h1>{{rating}}</h1> </span> </template> <script> ...

How do I disable scrolling while the animation is running in CSS?

Is there a way to disable scrolling while animating in CSS without using overflow:hidden on the body tag? ...

Preventing absolute div from spilling out of its parent container

Within a parent container, I have a lengthy div. I believe that it needs to be positioned absolutely in order to allow horizontal scrolling. My goal is to only display the portion inside the parent div. I attempted setting overflow: hidden on the parent ...

Steps to duplicate a Vuex store and incorporate it into a fresh store

In my endeavor to create a method in Electron that allows for the duplication of Vuex commits from one Window to another using IPC, I aim to simplify developers' usage of the Vuex store across different browser windows without the need for manual IPC ...

Is there a way to customize the language used for the months and days on the DatePicker

Is there a way to change the language of the DatePicker (months and days) in Material UI? I have attempted to implement localization through both the theme and LocalizationProvider, but neither method seems to work. Here are some resources I have looked a ...