LoginSignup
9
5

More than 3 years have passed since last update.

Vue.js クラスとスタイルのバインディング

Posted at

クラスのデータバインディングの基本

  • クラスを動的に変更するにはv-bind:classを利用する
  • クラスの付け替えが楽になる
<p v-bind:class="{クラス名: 真偽値}">
js
var app = new Vue({
  el: '#app',
  data: {
    isLarge: true // 真偽値を定義
    }
})
html
<!-- isLargeがtrueなので、largeクラスが適用される-->
<p v-bind:class="{large: isLarge}">Hello Vue.js!</p>

複数のクラスを動的に切り替える

  • カンマ区切りで、複数のクラスを指定できる。
html
<p v-bind:class="{クラス名: 真偽値, クラス名: 真偽値, ...}">
html
<p v-bind:class="{large: isLarge, 'text-danger': hasError}">Hello Vue.js!</p>

'text-danger'のように、クラス名にハイフンを含む場合は''(シングルクォート)で囲む。

プレーンなクラス属性と共存させる

一般的なクラス定義と、データバインディングしたクラスは共存できる。

<p class="クラス名" v-bind:class="{クラス名: 真偽値, クラス名: 真偽値, ...}">

配列構文によるクラスのデータバインディング

v-bind:classにクラスのリストを渡す事で展開できる

<p v-bind:class="[プロパティ名, プロパティ名, ...]">
js
data: { // dataにクラス名を持ったプロパティを定義
  largeClass: 'large', 
  dangerClass: 'text-danger'
}
html
<!-- クラスを適用するにはブランケットで囲む -->
<p v-bind:class="[largeClass, dangerClass]">Hello Vue.js!</p>

<!-- <p class="large text-danger">Hello Vue.js!</p>

オブジェクトのデータを利用する

複数のクラスをテンプレート(HTML)に書くと見通しが悪くなるので、オブジェクトで定義してv-bind:classに渡すことができる。

<p v-bind:class="オブジェクト">
js
data: {
  classObject: { //クラスのオブジェクトを定義
    large: true,
    'text-danger': true
    }
}
html
<!-- largeクラスとtext-dangerクラスが適用される -->
<p v-bind:class="classObject">Hello Vue.js!</p>

クラスの条件に三項演算子を使う

html
<!-- isTrueがtrueの時、trueClassクラスが適用される -->
<p v-bind:class="isTrue ? trueClass : '' ">Hello Vue.js!</p>

三項演算子の結果に関わらず、常に適用したいプロパティがある場合は[]で囲んでカンマで区切る。

html
<!-- fooClassは常に適用される -->
<span v-bind:class="[isTrue ? trueClass : '', fooClass ]">

インラインスタイルのデータバインディング

  • インラインスタイルを動的に変更するにはv-bind:styleを利用する

dataオプションに、インラインスタイルで使用したいプロパティをセット

js
data: {
    color: 'blue',
    fontSize: 48
}

v-bind:styleでデータバインディングさせたインラインスタイルを適用できる。

CSSのプロパティ名はキャメルケースにする必要がある。

html
<p v-bind:style="{color: color, fontSize: fontSize + 'px'}">Hello Vue.js!</p>

<!-- <p style="color: blue; font-size: 48px;">Hello Vue.js!</p> -->

ケバブケースで書きたいときは''(シングルクォート)で囲う

html
<p v-bind:style="{'font-size': fontSize + 'px'}"></p>

また、クラスのようにオブジェクトを渡すこともできる。

js
data: {
  styleObject: { // オブジェクトを定義
    color: 'blue',
    fontSize: '48px'
    }
}
html
<p v-bind:style="styleObject"></p>

<!-- <p style="color: blue; font-size: 48px;">Hello Vue.js!</p> -->
9
5
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
9
5