I am trying to use some methods and functions to generate a predefined tailwind class name for a component. The class name works fine as a static form. but when I use the computed method and my functions there wouldn't be any style for the component.
const getClass = computed(()=>{
return useColorAsBackgroundClass(props.color, props.shade)
})
This is the function that generates a string of the form "-bg--l-green-50" which is completely acceptable by static classing
<div class="-bg--l-green-50"></div> <!-- works fine --!>
I tried using the code as v-bind()
inside the var()
method for css. I also tried v-bind()
alone by adding var() for the returned text of the computed.
Also
<button :class="{getClass}" type="button">
hi
</button>
doesn't work, not {} or [].
As per the documentation:
The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:
Don’t construct class names dynamically
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
In the example above, the strings
text-red-600
andtext-green-600
do not exist, so Tailwind will not generate those classes. Instead, make sure any class names you’re using exist in full:Always use complete class names
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
You could:
Have the entire class in a prop
(ensuring the file that contains the component
usage is covered by the content
file globs in the Tailwind configuration):
<component color-class="-bg--l-green-50" …>
<button :class="colorClass">
Have a dictionary for color
and shade
to Tailwind class names (ensuring the file that the dictionary is defined is covered by the content
file globs in the Tailwind configuration):
const DICTIONARY = {
'l-green': {
50: '-bg--l-green-50',
60: '-bg--l-green-60',
70: '-bg--l-green-70',
80: '-bg--l-green-80',
// …
}
}
const useColorAsBackgroundClass = (color, shade) => {
// …
return DICTIONARY[color][shade];
}
safelist
the classes, if you have a limited number of known colors:
module.exports = {
safelist: [
{ pattern: /^-bg--l-(green|red|blue)-\d+$/ },
// …
],
// …
];