JSFiddle - React, Tailwind, and code Playground

by mogu10

HTML

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="el1">
<div 
  class="demo" 
  @click="attachRed = !attachRed"
  :class="devClasses"  
>①</div>
<div class="demo" :class="{red: attachRed}">②</div>
<div class="demo" :class="[color, {red: attachRed}]" :style="myStyle">③</div>
<input type="text" v-model="color">
<input type="text" v-model="width">
<hr>
<div class="demo" :style="[myStyle, {height: width + 'px'}]">④</div>
<input type="text" v-model="width">

<br><br><br><br><br>
<p>① @click="attachRed = !attachRed"でdata内attachRedのfalseとtrueをチェンジ<br>
trueの場合・falseの場合でなんのクラスをつけたいのか、それをcomputedに記載<br>
そのクラスをつけたいので、クラスバインド:class="devClasses"としている</p>
<p>② オブジェクト構文。{}<br>
:classで.redバインドしたい。<br>
バインドする時の条件がattachRedがtrueの時<br>
つまり①をクリックしてattachRedがtrueに切り替わった時に連動して.redが有効になる</p>
<p>computedではなくmethodsで書く場合<br>
:class="devClasses()"と書く必要あり<br>
computedはプロパティ、methodsは関数のため
</p>
<p>③ 配列構文。[]のArray。<br>
[color, {red: attachRed}]
入力して色を変えることもできるし、入力がなくてattachRedがtrueになれば赤になる</p>
<p>③と④は同じmyStyleを使っているため連動しちゃう<br>
これを防ぐには…</p>
</div>

CSS

.demo {
    background-color: pink;
    width :50px;
    height: 50px;
    margin: 10px;
}

.red {
    background-color: red;
  }

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

JavaScript

new Vue({
el: '#el1', 
data: {
	attachRed: false,
  color: 'green',
  width: 50
},
computed: {
	devClasses: function() {
  	return {
    	red: this.attachRed, 
      blue: !this.attachRed
    };
      
  },
  myStyle: function() {
  	return {
    	width: this.width + 'px'
    }
  },
}
});