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

Adjust the Bootstrap settings to center the title on the navbar and shift the logout button to the right side

Is there a way to centrally align the title "My project" in the navbar while also keeping the logout button on the right of the same line as the title? <div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="contain ...

Eliminate any vacant areas within a container and shift the container, along with its contents, on the webpage

I want to eliminate the empty space within the container while maintaining some spacing around the black box, and ensure responsiveness. Additionally, how can I shift the container with its content downwards and to the right of the webpage, while still ke ...

Compiling ES6 code into modules with the help of Webpack

Struggling to compile ES6 code into a file using Webpack? Wondering why the resulting code is not usable as it should be? Important Note: This code is intended to be a plugin for VueJS To begin, I have a basic file that exports a single function like t ...

The button component is unresponsive

An app was developed with a component containing signin and signup buttons on the right side. However, there is an issue where the Sign up button is not clickable. Below is the code snippet for the component => import React from "react"; expo ...

The beginning of my HTML input is not at the top of the page

I have a query regarding the custom input line I created recently. When I adjust the height of the input, instead of aligning with the top, the text appears vertically centered. Moreover, the text does not wrap to a new line once it reaches the outermost ...

Can a class be created using a PHP variable as its basis?

Is it possible to define the body color based on a variable in PHP? I have been experimenting with different methods to achieve this. <?php $seperate_sitting_yes = "Yes"; if($seperate_sitting_yes == "Yes") { ?> <style type="text ...

ReactForms Deprication for NgModel

According to Angular, certain directives and features are considered deprecated and could potentially be removed in upcoming versions. In a hypothetical scenario, let's say I am using NgModel with reactive forms, which Angular has marked as deprecate ...

Issue: The key length and initialization vector length are incorrect when using the AES-256-CBC encryption algorithm

Within my coding project, I have developed two essential functions that utilize the AES-256-CBC encryption and decryption algorithm: import * as crypto from "crypto"; export const encrypt = (text: string, key: string, iv: string) => { con ...

Understanding the Vue lifecycle methods for updating Vuex state

Utilizing Vue and Vuex components, the code within my component consists of: computed: { ...mapState({ address: state => state.wallet.address }) }, The functionality operates smoothly in the user interface. However, my objective is to invoke a ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...

A guide to developing reusable functions in Vue.js

In my Vuejs file, there is a function that calls another function imported from a JavaScript file. Check out the demo in Demo.vue: import Data from "demofile.js" created(){ this.getResult() } methods(){ async getResult(){ Data.example() // Fetch ...

Leveraging GSAP and Vue by utilizing props to dynamically calculate a maxWidth

I am working on animating buttons in my application using GSAP. The idea is that when a user clicks the button, it should animate the maxWidth of the button. I want this to be dynamic by adding a percentage of the max width set using props. Is it possibl ...

Is Jasmine brushing off TypeScript test files?

I'm diving into my first project with Jasmine, and despite following a tutorial, I'm encountering some hurdles right from the start. After installing jasmine-node, typings, and typescript, I executed: typings install dt~jasmine --save-dev --glo ...

Positioning a div relative to another div using the pos:fixed attribute

Is there a way to make a fixed position div relative to its parent div instead of the window using only CSS? I want a sticky block that follows the content while scrolling with the page, and stays in place even when the window is resized. I know this can ...

When trying to pass props into setup using VueJS 3 Composition API and TypeScript, an error may occur stating: "Property 'user' does not exist on type"

I need help figuring out why TypeScript is not recognizing that props.user is of type UserInterface. Any advice or guidance would be greatly appreciated. You can reach me at [email protected], [email protected], [email protected]. This seem ...

React/Typescript: The object might be null

I am currently converting a React component to TypeScript. The component is making an API call, and although I believe my interfaces are correctly set up, I seem to be passing the types incorrectly. How can I resolve the two errors in the Parent componen ...

Using Vue JS to display information conditionally within a single component

I currently have a component that dynamically displays the data from an array of objects. However, I want the component to display only one object based on a specific condition. Is it possible to show either one object or another depending on the value o ...

Typescript and Mongoose Schema - Common Design Mistakes

I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with: import { Document, Schema, Model, model} from "mongoose"; export interface IApplication { id: number; name ...

Issue with Hover Effect on Safari Browser

Encountering a peculiar issue exclusively in Safari - when hovering over a link in the header, the links to the right of the hovered-over link alter their size (appearing smaller) during the hover animation. Once the animation concludes, these links revert ...

Is it possible to nest axios post requests within another axios post request?

Can someone assist me with getting the session ID from the API to utilize it as a part of my input for an Axios POST request in order to retrieve user information? Despite double-checking my code thoroughly, I keep encountering a session expired error. Any ...