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]
}