Vue 中的动态类无法正确生成 Tailwind 颜色的任何解决方案吗?

问题描述 投票:0回答:1
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年开始询问的人似乎也还没有得到答案。

vuejs3 tailwind-css
1个回答
0
投票

根据文档

Tailwind 如何提取类名的最重要含义是,它只会查找源文件中以完整不间断的字符串形式存在的类。

如果您使用字符串插值或将部分类名连接在一起,Tailwind 将找不到它们,因此不会生成相应的 CSS:

不要动态构造类名

<div class="text-{{ error ? 'red' : 'green' }}-600"></div>

在上面的示例中,字符串

text-red-600
text-green-600
不存在,因此 Tailwind 不会生成这些类。 相反,请确保您使用的任何类名完整存在:

始终使用完整的类名

<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+$/ },
        // …
      ],
      // …
    ];
    
© www.soinside.com 2019 - 2024. All rights reserved.