computed: {
background() {
switch (this.color) {
case "blue-500":
return "bg-blue-500" // this working
case "orange-600":
return "bg-orange-500"
default:
return `bg-${this.color}` // but not this, only work if cached
}
}
我正在用这样的东西来实现它
<template>
<div :class="`fixed p-1 px-4 right-1/2 translate-x-1/2 shadow-xl rounded-full text-sm text-center text-white ${background} z-100 transition-all`" :style="style">
<span><i v-if="loading" class="fa-solid fa-spinner animate-spin mr-1"></i></span><span class="whitespace-nowrap">{{ text }}</span>
</div>
</template>
从2022年开始询问的人似乎也还没有得到答案。
根据文档:
Tailwind 如何提取类名的最重要含义是,它只会查找源文件中以完整不间断的字符串形式存在的类。
如果您使用字符串插值或将部分类名连接在一起,Tailwind 将找不到它们,因此不会生成相应的 CSS:
不要动态构造类名
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
在上面的示例中,字符串
和text-red-600
不存在,因此 Tailwind 不会生成这些类。 相反,请确保您使用的任何类名完整存在:text-green-600
始终使用完整的类名
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
你可以:
将整个类放在传递给组件的变量中,例如
<Component background="bg-red-400"/>
<template>
<div :class="`… {background} …`" …>
扩展您拥有的词典:
computed: {
background() {
switch (this.color) {
case "blue-500":
return "bg-blue-500" // this working
case "orange-600":
return "bg-orange-500"
case "red-500":
return "bg-red-500"
case "purple-500":
return "bg-purple-500"
…
default:
console.error(`Color ${this.color} is not supported`);
return '';
}
}
使用
style
属性,从 Tailwind 获取颜色):
import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from './tailwind.config.js'
const fullConfig = resolveConfig(tailwindConfig)
computed: {
background() {
// May need to do additional logic for nested color values, like blue.500.
return fullConfig[this.color];
}
<template>
<div … :style="{ ...style, backgroundColor: background }">
safelist
类别,如果您的已知颜色数量有限:
module.exports = {
safelist: [
{ pattern: /^bg-(red|green|blue)-\d+$/ },
// …
],
// …
];