vue.js入門_14_クラスとスタイルのデータバインディング

by s9iwork

HTML

<div id="app">
  <h2>①class1つ付与</h2>
  <p>Hello <span v-bind:class="{large: isLarge}">Vue.js</span></p>
  <h2>②class2つ付与</h2>
  <p>Hello <span v-bind:class="{large: isLarge, 'text-danger': hasError}">Vue.js</span></p>
  <h2>③プレーンなclassあり</h2>
  <p>Hello <span class="italic" v-bind:class="{large: isLarge}">Vue.js</span></p>
  <h2>④配列で複数指定</h2>
  <p>Hello <span v-bind:class="[largeClass, dangerClass]">Vue.js</span></p>
  <h2>⑤dataプロパティで定義されたclassを指定</h2>
  <p>Hello <span v-bind:class="danger">Vue.js</span></p>
  <h2>⑥三項演算子で指定</h2>
  <p>Hello <span v-bind:class="[isLarge ? 'large' : smallClass, italicClass]">Vue.js</span></p>
  <h2>⑦インラインスタイルで指定</h2>
  <p>Hello <span v-bind:style="{color: orangeColor, 'font-size': smallValue}">Vue.js</span></p>
  <h2>⑧インラインスタイルでdataプロパティで定義したスタイルを指定</h2>
  <p>Hello <span v-bind:style="smallOrange">Vue.js</span></p>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.js"></script>

CSS

.large {
  font-size: 1.5rem;
}

.small {
  font-size: 0.5rem;
}

.text-danger {
  color: #F00;
}

.italic {
  font-style: italic;
}

h2 {
  font-size: 1.2rem;
}

h2::before{
  content: "■";
}

JavaScript

new Vue({
  el: '#app',
  data: {
    isLarge: true,
    hasError: true,
    largeClass: 'large',
    smallClass: 'small',
    italicClass: 'italic',
    dangerClass: 'text-danger',
    danger: {
      large: true,
      'text-danger': true
    },
    smallValue: '0.5rem',
    orangeColor: 'orange',
    smallOrange: {
      color: 'orange',
      'font-size': '0.5rem'
    }
  }
})