classStyleBinding
v-bind를 이용한 class binding을 알아보고, ref와 Array,reactive,computed의 관계를 알아보자

class binding


<script setup>
import { ref, reactive,computed } from 'vue'

const count = ref(0);
const countState = reactive({
  counts: count, 
});

let tag = ref(true);

const computedObject = computed(
() => {
  return {
    testClass: tag.value
  }
}
)

const classObject = reactive({
  active: tag, //.value = no
  'text-danger': false
})



const activeClass = ref('activeClass')
const arrayObject = reactive([activeClass])


const countUp = () =>{
  console.log('count:', countState.counts);
  return countState.counts++;
}
const changeRef = () =>  {
  tag.value = !(tag.value);
  console.log('tag:', tag.value);
}
const chageObject = () =>  {
  classObject.active = !(classObject.active);
  console.log('classObject.active', classObject.active);
}
const chageArray = () =>  {
  arrayObject[0].value = arrayObject[0].value + 's';
  console.log('arrayObject[0].value', arrayObject[0].value);
}
const chageComputed = () =>  {
  computedObject.testClass = !(computedObject.testClass)
  console.log('computedObject.testClass', computedObject.testClass);
}

</script>

<template>
  <button @click="countUp">
    countUp: {{ countState.counts }}
  </button>
  <br>
  
  <button @click="changeRef">
    ref is true ? {{ tag }}
  </button>
  <br>
  
  <button @click="changeObject">
    object ? {{ classObject.active }}
  </button>
  <br>
  
  <button @click="chageArray">
    array ? {{ arrayObject[0].value }}
  </button>
  <br>
  
  <button @click="chageComputed">
    computed ? {{ computedObject.testClass }}
  </button>
  <br>
  
  
  
  <div class="A" :class="computedObject">
    A Box
  </div>
  <div class="B" :class="{ testClass2: tag }">
    B Box
  </div>
  <div class="C" :class="classObject">
    C Box
  </div>
  <div class="D" :class="[activeClass]">
    D Box
  </div>
  <div class="E" :class="computedObject">
    E Box
  </div>
</template>

ref와 객체의 조합

ref + reactive

let tag = ref(true);
const classObject = reactive({
  active: tag, //.value = no
  'text-danger': false
})
const chageObject = () =>  {
  classObject.active = !(classObject.active);
  console.log('classObject.active', classObject.active);
}
  • ref + reactive => .value 붙일 필요가 없다

ref + computed

let tag = ref(true);
const computedObject = computed(
() => {
  return {
    testClass: tag.value
  }
}
)

const chageComputed = () =>  {
  computedObject.testClass = !(computedObject.testClass)
  console.log('computedObject.testClass', computedObject.testClass);
}

  • ref + computed => .value 붙여야함
  • 대신 computed에서 값을 변경하여도 ref는 반응이 없다. 즉, 단방향이다

ref + Array

const activeClass = ref('activeClass')
const arrayObject = reactive([activeClass])

const chageArray = () =>  {
  arrayObject[0].value = arrayObject[0].value + 's';
  console.log('arrayObject[0].value', arrayObject[0].value);
}
  • reactive객체 안에서는 .value를 붙이지않고, reactive객체를 사용할 땐 .value를 붙인다

소스코드 바로확인하기

참고자료: Vue3 완벽 마스터: 기초부터 실전까지 - “기본편”

댓글 쓰기