LoginSignup
0
0

More than 3 years have passed since last update.

Vue.jsでCSSのスタイルをデータに紐付ける方法

Posted at

classをデータにバインディング(紐付け)する

パターン1

<div id="app">
  <h1 :class="classObject">Text</h1>
  <button @click="isActive = !isActive">switch</button>
</div>

<style>
  .red {
    color: red;
  }
  .bg-blue {
    background-color: blue;
  }
</style>

<script>
  new Vue({
    el: "#app",
    data: {
      isActive: true
    },
    computed: {
      classObject: function () {
        return {
          red: this.isActive,
          'bg-blue': !this.isActive
        }
      }
    },
  })
</script>

パターン2

<div id="app">
  <h1 :class="classObject">Text</h1>
  <button @click="isActive = !isActive">switch</button>
</div>

<style>
  .red {
    color: red;
  }
  .bg-blue {
    background-color: blue;
  }
</style>

<script>
  new Vue({
    el: "#app",
    data: {
      isActive: true
    },
    computed: {
      classObject: function () {
        return {
          red: this.isActive,
          'bg-blue': !this.isActive
        }
      }
    },
  })
</script>

styleをデータにバインディング(紐付け)する

<div id="app">
  <h1 :style="{ color: textColor, 'background-color': bgColor }">Text</h1>
  <h1 :style="styleObject">Text</h1>
</div>

<script>
new Vue({
  el: "#app",
  data: {
    textColor: 'red',
    bgColor: 'blue',
    styleObject: {
      color: 'red',
      'background-color': 'blue'
    }
  }
})
</script>
0
0
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
0
0