What is the process for converting the color names from Vuetify's material design into hexadecimal values within a Vue component?

I'm looking to obtain a Vuetify material design color in hexadecimal format for my Vue component's template. I want to use it in a way that allows me to dynamically apply the color as a border, like this:

<div :style="`border: 5px solid ${ myHexadecimalColor('amber lighten-2') }`">
</div>

Although I've checked out the SASS Variables and Colors sections in the Vuetify documentation, I couldn't find a straightforward solution to convert color names to their hexadecimal values.

The colors are defined in Vuetify's GitHub repository at vuetify/packages/vuetify/src/styles/settings/_colors.scss, but I'm unsure how to access these Sass variables in my Vue single-file component.

If anyone knows the best method to translate Vuetify material design color names into hexadecimal values, please share!


Bonus - Custom Vuetify 2 Function for Color Conversion

Borrowing from Boussadjra Brahim's solution, I created a quick function to convert color names to hexadecimal codes and added it below as a Vue mixin for potential usefulness:

Example: hexColor('amber lighten-2') returns #FFD54F

import colors from 'vuetify/lib/util/colors'

methods: {
  hexColor: (name) => {
    const [nameFamily, nameModifier] = name.split(' ')
    const shades = ['black', 'white', 'transparent']
    const util = {family: null, modifier: null}
    if (shades.find(shade => shade === nameFamily)){
      util.family = 'shades'
      util.modifier = nameFamily
    } else {
      const [firstWord, secondWord] = nameFamily.split('-')
      util.family = `${ firstWord }${ secondWord
        ? secondWord.charAt(0).toUpperCase() + secondWord.slice(1)
        : '' }`
      util.modifier = nameModifier 
        ? nameModifier.replace('-', '') 
        : 'base'
    }
    return colors[util.family][util.modifier]
  }
}

Update - Enhanced Vuetify 3 Color Conversion Function

Below is an updated version of hexColor() for Vuetify 3 due to changes in color naming conventions from e.g. blue lighten-2 to blue-lighten-2:

import colors from 'vuetify/lib/util/colors'

hexColor: (name) => {
  const baseColors = ['red','pink','purple','deep-purple','indigo','blue','light-blue','cyan','teal','green','light-green','lime','yellow','amber','orange','deep-orange','brown','blue-grey','grey']
  const shades = ['black', 'white', 'transparent']
  const match = [...baseColors,...shades].find(c => name.startsWith(c)) || null
  const remainder = match 
    ? name.slice(match.length) 
    : null
  const base = match.replace(/[-_](.)/g, (_, char) => char.toUpperCase());
  const variety = remainder 
    ? remainder.replaceAll('-','')
    : 'base'
  const nameStructured = shades.find(shade => match === shade) 
    ? { base:'shades', variety:base}
    : { base:base, variety:variety}
  return colors[nameStructured.base][nameStructured.variety]
}

Answer №1

To utilize the colors in your component, import them first and then use the following modifier to access the color:


import colors from 'vuetify/lib/util/colors'

....

<div :style="`border: 5px solid ${colors['amber']['lighten2']}`"></div>

Answer №2

While the existing solution is accurate, I believe a more comprehensive function should be able to interpret theme-colors (like success, error) and their variations (e.g. success darken-2), as well as manage cases where colors are provided in hex, rgb, or rgba formats.

Below is a function that I integrated into a mixin to address these requirements:

import colors from 'vuetify/lib/util/colors';
...
methods: {
    translateColor(color) {
        if ('string' !== typeof color || color.trim().length == 0) {
            return color;
        }
        if (color.startsWith('#') || color.startsWith('rgb')) {
            return color;
        }
        const themeColors = Object.keys(this.$vuetify.theme.currentTheme);
        const themeColorIndex = themeColors.indexOf(color);
        if (themeColorIndex > -1) {
            return this.$vuetify.theme.currentTheme[color];
        }
        let baseColor;
        let shade;
        if (color.includes(' ')) {
            const [bc, s] = color.split(' ');
            baseColor = bc;
            shade = s;
        }
        else {
            baseColor = color;
            shade = 'base';
        }
        const generalColors = Object.keys(colors);
        const generalColorsIndex = generalColors.indexOf(baseColor);
        const themeColorsShadeIndex = themeColors.indexOf(baseColor);
        if (generalColorsIndex > -1 && shade) {
            const fixedShade = shade.toLowerCase().replace('-', '');
            const co = colors[generalColors[generalColorsIndex]];
            return co[fixedShade];
        }
        else if (themeColorsShadeIndex > -1 && shade) {
            const fixedShade = shade.toLowerCase().replace('-', '');
            const co = this.$vuetify.theme.parsedTheme[themeColors[themeColorsShadeIndex]]
            return co[fixedShade];
        }
        return color;
    }
}

Although there might be room for improvement, the key concept is the ability to process colors from both standard Material Design palettes and custom theme-defined colors.

Answer №3

Revamped Solution for Vue3 / Vuetify 3

Sharing the method I implemented in my recent Nuxt 3 project:

import colors from "vuetify/lib/util/colors";
import { vuetify } from "~/plugins/vuetify";

export default function convertColorToCss(colorCode?: string): string {
  if (typeof colorCode !== "string" || colorCode.trim().length === 0) {
    return colorCode as string;
  }
  if (colorCode.startsWith("#") || colorCode.startsWith("rgb")) {
    return colorCode;
  }
  const themeColors = vuetify.theme.current.value.colors;
  const colorMap = new Map<string, string>([
    ["black", colors.shades.black],
    ["white", colors.shades.white],
    ["transparent", colors.shades.transparent],
  ]);
  const standardColors = [
    "red",
    "pink",
    "purple",
    "deepPurple",
    "indigo",
    "blue",
    "lightBlue",
    "cyan",
    "teal",
    "green",
    "lightGreen",
    "lime",
    "yellow",
    "amber",
    "orange",
    "deepOrange",
    "brown",
    "blueGrey",
    "grey",
  ] as const;
  standardColors.forEach((stdColor) => {
    colorMap.set(stdColor, colors[stdColor].base);
    colorMap.set(
      `${stdColor}-lighten-1`,
      colors[stdColor].lighten5
    );
    colorMap.set(
      `${stdColor}-lighten-2`,
      colors[stdColor].lighten4
    );
    colorMap.set(
      `${stdColor}-lighten-3`,
      colors[stdColor].lighten3
    );
    colorMap.set(
      `${stdColor}-lighten-4`,
      colors[stdColor].lighten2
    );
    colorMap.set(
      `${stdColor}-lighten-5`,
      colors[stdColor].lighten1
    );
    colorMap.set(`${stdColor}-darken-6`, colors[stdColor].darken1);
    colorMap.set(`${stdColor}-darken-7`, colors[stdColor].darken2);
    colorMap.set(`${stdColor}-darken-8`, colors[stdColor].darken3);
    colorMap.set(`${stdColor}-darken-9`, colors[stdColor].darken4);
  });
  for (const key in themeColors) {
    if (!key.startsWith("on-")) {
      colorMap.set(key, themeColors[key as keyof typeof themeColors]);
    }
  }
  const value = colorMap.get(colorCode);
  if (value) {
    return value;
  }
  return "";
}

Answer №4

One approach is to leverage the existing Vuetify helpers:

Specifically for Vuetify 2:

import { transformColor, isCssColor } from "vuetify/lib/util/colorUtils";
import colors from "vuetify/lib/util/colors";

const color = "primary";
const currentTheme = this.$vuetify.theme.currentTheme;
const cssColor = !isCssColor(color)
  ? transformColor(color, colors, currentTheme)
  : color;
console.log(cssColor);

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

Copy data from JSON file to Vue2 Google Maps markers

I recently started working on a basic Vue project. The project involves integrating a Google Map using the vue2-google-maps package. Additionally, I have a JSON file (or data.php) containing the following information: { "locations": [ { "nam ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

Issue with Photoswipe pswp class Not Getting Properly Cleared Upon Closing Image

My website has a Photoswipe image gallery from . The issue I'm facing is that the CSS class does not reset or clear after closing the gallery for the second time. For example, when a user opens item 1, the images are loaded into the picture div via A ...

Encountered an error with Aurelia webpack 4 when trying to load a necessary CSS file during runtime

I encountered a unique issue with webpack and aurelia that I can't seem to figure out. After creating a new webpack configuration based on online resources and official documentation, the compilation goes smoothly without any errors. However, during r ...

Transform the Data into JSON format

I need assistance converting my data into the correct JSON format. The current structure of my data is as follows: [ "{ id:001, name:akhilesh, }", "{ id:002, name:Ram, }" ] My goal is to transform the above data into valid J ...

What are the benefits of using Bower.js when npm is already functioning well?

When working in the main project directory, running the command npm init will create a file called "package.json". If I need to install dependencies such as angular, jQuery and bootstrap, I can use the following commands: npm install angular --save-de ...

Conceal the header and footer during the loading of particular pages

For my Angular 1.x application, I needed a way to hide the header and footer on specific pages. To achieve this, I added a 'navigateOut' data property to my state definitions. Using ng-if in my template, I was able to show/hide elements such as t ...

How to set up a MySQL database specifically for a quiz based on different "types"

I am a beginner in the world of HTML, PHP, JavaScript, and MySQL. I have developed a quiz using JavaScript and HTML, but now I believe I need a database to store all the questions and answers. I am currently using PHPMyAdmin to set up the database and tabl ...

jsx syntax highlighting issue in sublime text

When building React components in Sublime Text, I am encountering issues with syntax highlighting. It seems like something is not done correctly. Can anyone point me in the right direction? https://i.sstatic.net/MKJcS.png ...

Having difficulty locating the index of the column labeled `Clients` within a table; the result being -1

Having some trouble locating the index of the column name Customers within a table using jQuery/javascript. No matter what I try, it always returns -1 let tableDatacy = "Results_Table"; let columnName = "Customer"; let tableHeaders = [] ...

Troubleshooting compatibility issues between ExpressJS's res.render and AngularJS

I'm relatively new to Node.js, Express, and AngularJS. I'm currently working on a basic Sign-in feature that will redirect to another page upon successful sign-in. While I know I can use window.location for the redirection, I'm trying to uti ...

Determine whether the object is facing the specified position

I'm attempting to verify whether an object (this.target) is facing towards a particular position (newPosition). Here's what I currently have: new THREE.Matrix4().lookAt( newPosition, this.target.position, this.target.up ) == this.target.matrix ...

How can one develop a Progressive Web App using Vue.js?

I used to develop PWAs using vanilla JavaScript in the following way: importScripts('/src/js/idb.js'); importScripts('/src/js/utility.js'); const CACHE_STATIC_NAME = 'static-v4'; const CACHE_DYNAMIC_NAME = 'dynamic-v2&a ...

Element cannot be located following the addition of a className in the HTML document

When manually adding id, test-id or classname in an HTML file, it's important to note that Cypress may have trouble finding the element. For example, I have included 'Classname' here just for demonstration purposes. https://i.stack.imgur.co ...

Require a hard refresh when running npm watch command

When I'm working with Laravel and Vue JS, I find myself relying heavily on the npm run watch command. However, whenever I make changes to my VUE template, I always have to manually refresh the browser by pressing Ctrl+Shift+R or enabling "Disable cac ...

Explore the power of VueJS for creating stunning data visualizations using the Django API

As a newcomer to frontend development, I am currently working on designing a data visualization platform that interacts with the RestAPI provided by Django. The data I am dealing with is in the form of a nested array of JSON. The structure of the JSON dat ...

Updating the main Vue app's value from a Vuetify component in Vue - a step-by-step

I have two vue files, app.vue and logincomponent.vue. In logincomponent.vue, I created a template for a login box that communicates with the go backend in Wails. The code is working fine, but I am struggling to change the value in the main app.vue file. ...

Omit child DIV element in JavaScript and the Document Object Model

I have a situation with two div elements. One is <div class="card" id="openWebsite"> and the other is a sub-division <div class="card__btn"> Here's the issue: When someone clicks on the main div, they get red ...

What sets apart .addEventListener and .on() when it comes to including an event in Bootstrap 5?

I'm currently attempting to attach a listener to my modal in order to implement a certain behavior each time the modal is opened. As per the guidance from Bootstrap 5 documentation, you can achieve this by using: https://getbootstrap.com/docs/5.2/com ...

Create dynamic animations using AngularJS to transition between different states within an ng-repeat loop

Here's a simplified explanation of my current dilemma: I have an array containing a list of items that are being displayed in an Angular view using ng-repeat, like... <li ng-repeat="item in items"> <div class="bar" ng-style="{'width ...