본문으로 건너뛰기

Vue에 대한 100가지 질문

  1. 조건부 스타일링은 어떻게 하는가?
  • v-bind:class = "{ 클래스명 : 조건 }"처럼 넣으면 됩니다.
<h2
:class="{ highlight: isDone === false, 'text-red': userName === 'IU' }"
>오브젝트 형태의 동적 클래스</h2>
  • 이렇게 넣으면 됩니다.

출처

  1. vue 아키택쳐는 어떻게 되어 있는가?
  • vue는 컴파일을 먼저하고 virtual dom을 만들고 랜더링을 처리합니다.
  1. vue의 provider injection 패턴은 무엇인가?
  1. vue의 ref는 state와 signal 어떻게 다른가?

  2. vue는 ref와 일반 변수 이외 상태를 보관하는 방법이 있는가?

  • react는 useRef로 라이프 사이클과 무관하게 상태를 보관할 수 있습니다.

  • vue도 라이프사이클과 무관하게 데이터를 보관하거나 다른 방식들이 존재하는지 의문이 들었습니다.

  1. vue의 전체 API별 예시는 무엇인가?

여기서 모든 API를 표현하는 것은 비효율적인 것 같습니다.

  1. 스타일링을 자바스크립트 값 혹은 상태로 제어하는 방법은 무엇인가?

v-bind() in CSS로 해결하면 됩니다.

<script setup>
const theme = {
color: 'red',
};
</script>

<template>
<p>hello</p>
</template>

<style scoped>
p {
color: v-bind('theme.color');
}
</style>

놀랍게도 이렇게 사용하면 됩니다.

  1. 양방향 바인딩 예시를 보여주세요.

페이지에서 커스텀 input을 사용하는 경우가 해당합니다.

<template>
<input v-model="text" />
</template>

<script setup lang="ts">
const text = ref<string>('');
</script>

이것은 상위 컴포넌트에서 하위 컴포넌트에게 props로 ref를 전달하는 것입니다.

<template>
<input :value="text" @input="edit" />
</template>

<script setup lang="ts">
const props = withDefaults(defineProps<BoardSpaceProps>(), {
text: '',
});

const { text } = propToRefs(props);
const emit = defineEmits(['update:modelValue']);
const edit = (e) => {
// text.value = e.target.value;
emit('update:modelValue', e.target.value);
};
</script>

하위 컴포넌트에서 발생한 이벤트를 상위컴포넌트의 상태에 덮어쓰기를 하고 있습니다.

v-model arguments

toRef

  1. watch vs computed

watch는 옵저버 패턴이라고 생각하면 됩니다. 구독할 ref를 지정하고 값이 갱신할 때마다 실행할 함수를 대입하면 됩니다.

import { ref, watch } from 'vue';

const count = ref(0);

watch(count, (newCount) => {
console.log(`new count is: ${newCount}`);
});

computed는 구독할 ref를 찾고 그 값을 복사하고 계산을 처리합니다.

import { ref, computed } from 'vue';
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value = count.value + 1;
}

return { count, doubleCount, increment };
});