Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Vue.js 入門 vol.3

参考サイト

https://jp.vuejs.org/v2/guide/class-and-style.html

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

<!-- isActiveがtrueの場合, classはactiveになる -->
<div v-bind:class="{ active: isActive }"></div>
<!-- hasErrorがtrueの場合、text-dangerが有効になる -->
<div class="static"
     v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>
data: {
  isActive: true,
  hasError: false
}
//上記のようにデータを与えた場合以下のhtmlのコードのよな結果になる。
<!-- 上記のコードの結果 -->
<div class="static active"></div>
  • 以下のようにも表示可能
<div v-bind:class="classObject"></div>
data: {
  classObject: {
    active: true,
    'text-danger': false
  }
}
  • 算出プロパティでもclassを制御可能。これが一般的ぽいぞ。
<div v-bind:class="classObject"></div>
//..
data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error, //isActiveがtrueで、errorが無い場合
      'text-danger': this.error && this.error.type === 'fatal',
    }
  }
}

配列構文

  • v-bind:class にクラスのリストを適用する配列を渡すことができます
<div v-bind:class="[activeClass, errorClass]"></div>
data:{
  activeClass: 'active',
  errorClass: 'text-danger'
}
<!-- 上記のコードの結果 -->
<div class="active text-danger"></div>
  • 条件付きでリストを切り替える場合
<div v-bind:class="[isActive ? activeClass : '', errorClass]">
<!-- isActiveがtrueのときだけ、activeClassが適用される -->

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

コンポーネントにおいて

  • 以下のようなコンポーネントがあったとして、いくつかのクラスを追加してみる。
Vue.component('my-component', {
  template: '<p class="foo bar">Hi</p>'
})
<my-component class="baz boo"></my-component>

<!--  結果として以下のhtmlが描画される -->
<p class="foo bar baz boo">Hi</p>
  • class bindingでも同様に機能する。
<my-component v-bind:class="{ active: isActive }"></my-component>
<!-- activeがtrueの場合は、以下の通り -->
<p class="foo bar active">Hi</p>

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

オブジェクト構文

  • v-bind:style はほとんどcssの文法に近い。
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data: {
  activeColor: 'red',
  fontSize: 30
}
  • templateをきれいにするために、styleObjectを作成するのもあり!
<div v-bind:style="styleObject"></div>
data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}
  • 配列構文もある。
<div v-bind:style="[baseStyles, overridingStyles]">
  • 複数の値も配列で設定できる。
<div v-bind:style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }">

条件付きレンダリング

  • v-if を使う。
<h1 v-if="ok">Yes</h1>
<h1 v-else>No</h1>
  • v-if をグループに適用したい場合は、<template>を使う。最終的に描画される結果は、