3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【tailwindcss】動的に当てるクラスを変えてみた

Last updated at Posted at 2025-05-14

ユーザーの選択したカテゴリごとに背景色を変えることが必要で、試行錯誤しながらやったのでそのメモです

一応動くけど...

最初とりあえず実装進めていた時は、背景色変えたいvueファイル全部に下のコード書いてました。
色変えたくなったら使用箇所全部修正するんか...?って思いますよねえ

switch (props.categoryId) {
    case 1: //カテゴリ1
        bgColorClass = "bg-red-400";
        break;
    case 2: //カテゴリ2
        bgColorClass = "bg-blue-300";
        break;
    case 3: //カテゴリ3
        bgColorClass = "bg-purple-300";
        break;
    // 〜〜〜〜
}

正気に戻った(最終的にやったこと)

冷静になって、色の指定は1箇所で完結させたいと思って実装したのが次です

// Color.ts
export const ColorList = {
  1: { //カテゴリ1
    normal: 'bg-red-700',
    light: 'bg-red-400',
  },
  2: { //カテゴリ2
    normal: 'bg-blue-600',
    light: 'bg-blue-300',
  },
  3: { //カテゴリ3
    normal: 'bg-purple-500',
    light: 'bg-purple-300',
  },
};

色指定用のtsファイルにカテゴリIDごとの色指定をして、使用したいvueファイルで、

<script setup lang="ts">
import {ColorList} from "@/script/Common/Color";

const props = defineProps({
  category: {
    type: Object,
    required: true,
  },
});
</script>

<template>
    <h2 :class="ColorList[props.category.id].light">{{props.category.name}}</h2>
</template>

これで色の変更したい時は、色指定のファイルだけ変えれば済むのでらくちんになりました〜

もっといいやり方がありそうな気はしつつ、受け取った値によって当てるクラスを変えたい場合に使いやすく変更できたと思います!

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?