22
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue の v-bind:class に複数の条件付き class を入れる簡単な方法(オブジェクト(ハッシュ)、配列)

Posted at

なぜ私は文字列連結なんてやってたのか。

オブジェクト(ハッシュ)

<div v-bind:class="{ active: true }"></div>
<!-- <div class="active"> -->
<div
  class="static"
  :class="{ active: true, 'text-danger': false }"
></div>
<!-- <div class="static active"> -->

インラインである必要はない。

<div v-bind:class="classObject"></div>

<script>
data: {
  classObject: {
    active: true,
    'text-danger': false
  }
}
</script>

<!-- <div class="active"></div> -->

配列

<div v-bind:class="[activeClass, errorClass]"></div>

<script>
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}
</script>

<!-- <div class="active text-danger"></div> -->

三項演算子で条件を指定することもできる。

<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>

なんと配列の内部でオブジェクト構文も使える。

<div v-bind:class="[{ active: isActive }, errorClass]"></div>

公式ドキュメント

22
17
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
22
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?