Vue.js - Dynamic styling with CSS

by hyeyoon

HTML

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <!-- Styling with CSS class - using Object -->   
  <div class="demo" @click="attachRed = !attachRed" :class="divClasses"></div>
  <div class="demo" :class="{red: attachRed}"></div>
  <div class="demo" :class="[color, {red: attachRed}]"></div>
  <hr>
  <!-- Styling with CSS class - using Name -->
  <input type="text" v-model="color">
  <hr>
  <!-- :style 안에 ''를 사용해도 되고 안해도 됨. 꼭 사용해야 할 경우는 - 등이 포함된 경우 -->
  <!-- 또는 cammel class를 사용하면 '' 사용안해도 됨 -->
  <!-- Styling without CSS class -->
  <div class="demo" :style="{backgroundColor: color}"></div>
  <div class="demo" :style="myStyle"></div>
  <div class="demo" :style="[myStyle, {height: width + 'px'}]"></div>
  <hr>
  <input type="text" v-model="color">
  <input type="text" v-model="width">
  {{ $data }}
</div>

SCSS

.demo {
  width: 100px;
  height: 100px;
  background: gray;
  margin: 10px;
  display: inline-block;
}
.red {
  background-color: red;
}
.green {
  background-color: green;
}
.blue {
  background-color: blue;
}

JavaScript

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