LoginSignup
2
0

More than 1 year has passed since last update.

【Vue.js】classをデータにバインディングする方法を図解で理解する。

Last updated at Posted at 2021-01-24

Vue.jsでは、v-bindでclass属性を設定した際に、下記の様なオブジェクトを渡すことにより、class属性の値を適用、不適用を切り替えることができる。

65b36a9f1709b0faed926d7badba95e5.png

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

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

<div id="app">
  <h1 :class="{red:true, blue:false}">Hello</h1>
</div>

<script>
  new Vue({
    el: '#app',
  })
</script>

2b23b34f73c55d908de52b09886428b4.png

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

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

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

<div id="app">
  <h1 :class="{red:false, blue:true}">Hello</h1>
</div>

<script>
  new Vue({
    el: '#app',
  })
</script>

##v-bindされたclass属性の値にオブジェクトを渡して動的に切り替える。

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

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

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

<div id="app">
  <h1 :class="classChange">Hello</h1>
  <button @click="change">切り替え</button>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      isActive: true
    },
    methods: {
      change: function () {
        this.isActive = !this.isActive
      },
    },
    computed: {
      classChange: function () {
        return {
          red: this.isActive,
          blue: !this.isActive,
        }
      }
    }
  })
</script>

データの流れ

IMG_4CD730BA51B2-1.jpeg

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