LoginSignup
6
2

More than 3 years have passed since last update.

【Vue.js】動的にクラス属性を切り替える方法

Last updated at Posted at 2020-12-19

はじめに

web アプリを作っている際、動的にクラス属性を切り替えたい場合があります。そのような場面で便利な Vue のv-bind:classについて書きます。

v-bind:class とは

Vueで使えるv-bindディレクティブの一つで、オブジェクトや配列を渡すことでそのデータプロパティの真偽値によってクラス属性の付与を切り替えることができます。

書き方

プロパティ値の真偽値が true のとき、v-bind:class で指定した html 要素にクラス名が付与さえます。逆に真偽値が false の場合はクラス名は付与されません。

<div v-bind:class="{クラス名:プロパティ値}">AAA</div>

実装例

以下では、v-bind:classによってblueクラスとredクラスをtoggledプロパティの真偽値によって付与しています。
methodsで指定されているtoggle関数はtoggledの真偽値を逆にする処理を実行します。

See the Pen VueJS - Usage of v-bind:class by TokioTakamiya (@tktaka) on CodePen.

参照

Vue.js : Class and Style Bindings

6
2
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
6
2