目次

目次

Vueのバインディングでスタイルを変えたかった話

山本早希
山本早希
最終更新日2021/07/09 投稿日2021/07/09

はじめに

開発している中で、「公開、非公開などのステータスの値によってCSSで背景の色を変えたい」ということがありました。 活性・非活性でSCCを変化させるやり方はわかるのですが 公開前, 公開中, 公開終了, 非公開という4つのステータスによってCSSを変化させるのはどうやるのだろうか、、、、 ということで記事にしていきます。

基本から

まず、活性・非活性でCSSを変えるのはこうでした。

template

<div :class="{ active: isActive }"></div>

script

data: {
  isActive: true
}

style

:not(.active)
  background-color $black
.active
  background-color $pink

isActivetrueのときは.activeが反映され、 falseのときは:not(.active)が反映されます。

挑戦

よし、同じようにやってみよう💪🏻

まずやったこと

statusの値

1:公開前
2:公開中
3:公開終了
4:非公開

template

<div
  class="status-wrap"
  :class="{
    'before': isBefore,
    'now': isNow,
    'end': isEnd,
    'private': isPrivate
  }"
>
  <p>{{ statusMessage }}</p>
</div>

script

export default {
  props: {
    status: {
      type: Number,
      required: true,
      default: 0
    }
  },
  data() {
    return {
      isBefore: false,
      isNow: false,
      isEnd: false,
      isPrivate: false
    }
  },
  computed: {
    statusMessage() {
      if (this.status === 1) {
        return '公開前'
      } else if (this.status === 2) {
        return '公開中'
      } else if (this.status === 3) {
        return '公開終了'
      } else if (this.status === 4){
        return '非公開'
      } else {
        return ''
      }
    }
  }
  // こんな感じの処理をやりたい
  // if (this.status === 1) {
  //   this.isBefore = true
  // } else if (this.status === 2) {
  //   this.isNow = true
  // } else if (this.status === 3) {
  //   this.isEnd = true
  // } else if (this.status === 4){
  //   this.isPrivate = true
  // }
}

style

.status-wrap
  display inline-block

  &.before
    background-color $pink

  &.now
    background-color $blue

  &.end
    background-color $gold

  &.private
    background-color $black

と書いてみたのですが、 コメントアウト箇所の処理をどうすれば良いのかわかりませんでした。

次の挑戦

template

<div class="status-wrap" :class="judgeStatus">
  <p>{{ statusMessage }}</p>
</div>

script

export default {
  === 略 ===
  computed: {
    judgeStatus() {
      if (this.status === 1) {
        this.isBefore = true
      } else if (this.status === 2) {
        this.isNow = true
      } else if (this.status === 3) {
        this.isEnd = true
      } else if (this.status === 4) {
        this.isPrivate = true
      }
    },
  === 略 ===
  }
}

これだと、クラスをどう結びつけるのかわかりませんでした。

出会った

う〜〜〜〜〜〜〜〜〜んと頭を抱えているときに出会った 3項演算子を使ったクラスバインディングを配列構文で書き換える

できそう💪🏻

template

<div
  class="status-wrap"
  :class="{
    'before': status === 1,
    'now': status === 2,
    'end': status === 3,
    'private': status === 4
  }"
>

できた!!!!!!!!!!!!!!!!!!!!!!!!!!

test.jpg 10%

さいごに

filtersを使えばよかったっぽい

template

<div
  class="status-wrap"
  :class="status | stateColor"
>

script

export default {
  filters: {
  // filterを使ってクラスを決定する
    stateColor(state) {
      if (state === 1) return 'before'
      if (state === 2) return 'now'
      if (state === 3) return 'end'
      if (state === 4) return 'private'
      return ''
    }
  },
  === 略 ===
}

山本早希

目次