uxtry

vue: Props 본문

Vue.js 3 주요 문법 (vue:)

vue: Props

uxtry 2024. 12. 19. 09:47

Props는 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달하기 위해 사용하는 방법입니다.  Props는 컴포넌트 간의 데이터 전달을 가능하게 하며, 이를 통해 컴포넌트 간의 재사용성과 독립성을 높일 수 있습니다. 아래 예제를 통해  Props의 기본개념과 활용법을 자세히 설명하겠습니다.

 

간단한 Props 전달

 

ParentComponent.vue

<template>
<div>
	<h1>부모 컴포넌트</h1>
    <!-- 자식 컴포넌트에 'title' Props 전달 -->
    <ChildComponent title="Hello Vue Props!" />
</div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
	component: {
    	childComponent,
    },
};
</script>

 

ChildComponent.vue

<template>
<div>
	<h2>자식 컴포넌트</h2>
    <p>{{title}}</p>
</div>
</template>

<script>
export default {
	props: {
    	title:{
         type: String, //props의 타입 설정
         required: true, //필수 여부 지정
        },
    },
};
</script>

★ Vue SFC Playground 코드 실행 →

  • ParentComponent에서 childComponenttitle이라는 데이터를 전달합니다.
  • ChildComponent는 전달 받은 title 값을 표시합니다.

 

Props의 주요기능과 활용법

 

1. 데이터 유형 검증

Props는 데이터를 전달받을 때 올바른 유형인지 검증할 수 있습니다. Vue에서는 type옵션을 사용하여 데이터 유형을 지정합니다.

props: {
	count:{
    	type: Number, //Number 타입만 허용
        required: true, //필수 Props로 설정
        default: 0, //기본값 설정
    },
},

 

2. 기본값 제공

필수 props가 아니더라도, default 옵션을 통해 기본값을 설정할 수 있습니다.

props:{
	isActive:{
    	type: Boolean,
        default: false,
    }
}

 

3. Props의 변경 금지

Props는 단방향 데이터 흐름을 따르므로, 자식 컴포넌트에서 직접 수정해서는 안됩니다. 수정이 필요할 경우, 자식 컴포넌트에서 이벤트를 통해 부모 컴포넌트에 알리고 부모 컴포넌트에서 상태를 변경해야 합니다.

 

Prop 변경 방지와 이벤트 통신

 

ParentComponent.vue

<template>
  <div>
    <ChildComponent :count="parentCount" @increment="incrementCount" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  data() {
    return {
      parentCount: 0,
    };
  },
  methods: {
    incrementCount() {
      this.parentCount++;
    },
  },
  components: {
    ChildComponent,
  },
};
</script>

 

ChildComponent.vue

<template>
<div>
	<p>Count: {{ count }}</p>
    <button @click="$emit('increment')">증가</button>
</div>
</template>

<script>
export default{
	props: {
    	count: {
         type: Number,
         required: true,
        }    
    }
}
</script>

★ Vue SFC Playground 코드 실행 →

  • ParentComponent에서 count값을 Prop으로 전달합니다.
  • ChildComponent는 prop의 값을 표시하며, 버튼 클릭 시 부모 컴포넌트의 count값을 증가시킵니다.

Vue.js에서 props는 데이터를 전달만 할 수 있고 수정은 불가능합니다. 이벤트 통신을 활용해 데이터를 관리합니다.

 

 

'Vue.js 3 주요 문법 (vue:)' 카테고리의 다른 글

vue: Single File Component  (0) 2024.12.19
vue: 컴포넌트 기초  (1) 2024.11.29
vue: Watch와 WatchEffect  (0) 2024.11.26
vue: 양방향 바인딩(v-model)  (0) 2024.11.22
vue: 이벤트 처리  (0) 2024.11.21