[Vue.js] TIL : v-model, setup script, 생명주기 훅

jade·2025년 2월 19일
0

1️⃣ v-model과 양방향 바인딩

v-model디렉티브는 양방향 데이터 바인딩을 지원하는 속성이다.

양방향 데이터 바인딩이란 화면의 데이터와 뷰 인스턴스가 항상 일치하는 것이다.

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

<script setup>
import {ref} from 'vue';

const inputText = ref('');
</script>

v-model디렉티브는 간편한 양방향 바인딩기능을 지원하지만, 내부적으로는 아래 코드와 같은 구조로 동작한다.

<template>
  <input type="text" :value='inputText' @input='inputText=$event.target.value" />
</template>

<script setup>
import {ref} from 'vue';

const inputText = ref('');
</script>

2️⃣ setup script 에서 data, computed, methods 등의 속성은 사용불가

대신, ref, computed 함수, defineEmits, defineExpose 등의 기능을 사용하여 대체할 수 있다. 이때 컴포넌트 옵션들의 의존성이 순서에 의해 결정되기 때문에 옵션 정의 시에 아래 예시와 같은 순서를 따라야한다.

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

// 1. props 정의: 컴포넌트에 전달되는 프롭스
const props = defineProps({
  // props 옵션들...
});

// 2. 데이터 선언: ref, reactive 등을 사용하여 컴포넌트의 반응형 데이터 선언
const count = ref(0);

// 3. 컴포지션 함수: 컴포넌트의 로직을 재사용 가능한 컴포지션 함수로 추출, 재사용 가능
const doubleCount = computed(() => {
  return count.value * 2;
});

// 4. 컴포넌트 옵션: 컴포넌트 옵션을 직접 사용하지 않고 선언된 변수와 함수로 로직을 작성
// computed 옵션 대신 computed 함수, watch 속성 대신 watch 함수 ...
watch(count, (newValue, oldValue) => {
  console.log('Count changed:', newValue, oldValue);
});

// 5. 기타 코드: 필요에 따른 기타 로직, 함수 정의
// 필요한 추가 로직이나 함수 등...
</script>

3️⃣ 생명주기 훅

profile
keep on pushing

0개의 댓글

관련 채용 정보